如何将文本元素定位到特定位置并在SVG中调整大小?

时间:2019-01-02 14:47:03

标签: javascript jquery svg svg-edit

我正在基于文本框中的输入值创建rect元素(从文本框中获取Height,Width,X和Y)。

创建rect并将其附加在父g元素中时。我正在创建一个文本元素,其中显示了新创建的矩形编号。我将该文本放置在 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 + ")");

创建的矩形可以任意大小,因此,为了缩放文本元素,我尝试了上面的转换代码。但是某种程度上它不起作用。我需要的是矩形的大小 RectNo 文本应显示在左上方,矩形的角,并应根据矩形的尺寸进行调整(调整高度和宽度的大小)

1 个答案:

答案 0 :(得分:0)

首先,我得到文本的宽度:let txtW = RectNo.getComputedTextLength();

下一步,我正在计算比例尺:scale = (width-13) / txtW;

我认为您需要在文本末尾加13个单位的间距。

同样在CSS中,我使用的是text{dominant-baseline:hanging},否则您将得到文本的一半。希望对您有所帮助。

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>