[英]How to position a text element to a specific position and resizable in SVG?
我正在基于文本框的输入值创建rect元素(从文本框获取Height,Width,X和Y)。
创建rect并将其附加在父g元素中时。 我正在创建一个文本元素来显示新创建的rect编号。我将此文本放置在rect的左上角。
这是我的代码(不是全部与问题相关)。在按钮的onclick事件上调用。
//Creating <rect>
Rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
Rect.setAttributeNS(null, "id", "rectId");
Rect.setAttributeNS(null, "x", x); //getting x from textbox
Rect.setAttributeNS(null, "width", width); //getting width from
textbox
Rect.setAttributeNS(null, "y", y); //getting y from textbox
Rect.setAttributeNS(null, "height", height); //getting height from
textbox
Rect.setAttributeNS(null, "fill", "none");
grp.appendChild(Rect);
//Creating <text> for Rect Num
RectNo = document.createElementNS('http://www.w3.org/2000/svg', 'text');
RectNo.setAttributeNS(null, "id", "textNo");
numTxt = document.createTextNode("RectNum_"+(any number));
RectNo.appendChild(numTxt);
grp.appendChild(RectNo);
scale = (width - (width-13)) / width; //(width of rect)
posX = x+1; //(x of rect)
posY = y+3; //(y of rect)
RectNo.setAttribute("transform", "translate(" + posX + "," + posY + ")
scale(" + scale + ")");
创建的rect可以是任何大小 ,因此为了缩放文本元素,我尝试了上面的transform代码。 但是无论如何它不起作用。我需要的是无论矩形大小是多大或小 , RectNo文本都应该出现在rect的左上角,并且应该根据 rect 进行调整(调整大小和宽度)尺寸。
首先,我得到文本的宽度: let txtW = RectNo.getComputedTextLength();
接下来,我要计算比例尺: scale = (width-13) / txtW;
我认为您需要在文本末尾增加13个单位的间距。
同样在CSS中,我使用的是text{dominant-baseline:hanging}
,否则您将获得文本在rect外的一半。 希望对您有所帮助。
let x=10,y=10,width=100,height=50,any_number = 3; //Creating <rect> Rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); Rect.setAttributeNS(null, "id", "rectId"); Rect.setAttributeNS(null, "x", x); //getting x from textbox Rect.setAttributeNS(null, "width", width); //getting width from textbox Rect.setAttributeNS(null, "y", y); //getting y from textbox Rect.setAttributeNS(null, "height", height); //getting height from textbox Rect.setAttributeNS(null, "fill", "#d9d9d9"); grp.appendChild(Rect); //Creating <text> for Rect Num RectNo = document.createElementNS('http://www.w3.org/2000/svg', 'text'); RectNo.setAttributeNS(null, "id", "textNo"); numTxt = document.createTextNode("RectNum_"+ (Math.random()*100)); RectNo.appendChild(numTxt); grp.appendChild(RectNo); let txtW = RectNo.getComputedTextLength(); scale = (width-13) / txtW; posX = x+1; //(x of rect) posY = y+3; //(y of rect) RectNo.setAttribute("transform", "translate(" + posX + "," + posY + ")"+"scale(" + scale + ")");
svg{border:1px solid} text{dominant-baseline:hanging}
<svg viewBox="0 0 200 100"> <g id="grp"></g> </svg>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.