简体   繁体   English

Snap.svg和动态文本

[英]Snap.svg and dynamic text

I'm trying to place text dynamically into an svg created by Snap, this is what I tried: 我试图将文本动态地放置到Snap创建的svg中,这是我尝试的方法:

this.setContent(
  `<svg id="${this.svgId}"></svg>`
);

var snap = Snap($(`#${this.svgId}`)[0]);
text = "asdfsdfsdsfd";

var rect = snap.paper.rect(0, 0, 50, text.length*3 + 4, 10);
snap.text(1.5,10, text);

console.log("rect", rect);
console.log("snap", snap);

rect.attr({
  fill: "#FFFFFF",
  fillOpacity: 0.6,
});

I get this: 我得到这个: 在此处输入图片说明

I want the rectangle to be just a little bigger than the text, but there must be a better way to do it than to calculate the length and height of the text, and that's assuming the font size won't change. 我希望矩形比文本大一点,但是必须有一个比计算文本的长度和高度更好的方法,这是假定字体大小不会改变。

This is the only result I found regarding text in the snap docs: http://snapsvg.io/docs/#Paper.text 这是我在快照文档中找到的关于文本的唯一结果: http : //snapsvg.io/docs/#Paper.text

You could try using getBBox() on the text element, and use that to figure the size of the rect. 您可以尝试在文本元素上使用getBBox(),然后使用它来计算rect的大小。 getBBox() wll give you the x,y,width,height,x2,y2 figures to help. getBBox()将为您提供x,y,width,height,x2,y2的数字来帮助您。

var text = s.text(0,0,'blah blah')
var bb = text.getBBox();
var rect = s.rect(bb.x, bb.y, bb.width, bb.height )

Adjusting with offsets for whatever padding etc that you want. 用偏移量调整所需的填充等。 You may also need to allow for stroke widths, as I don't think that's included. 您可能还需要考虑笔划宽度,因为我认为这不包括在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM