我有一个矩形,我试图在其中放置一个文本和一个小图像(图像和文本为内联)。图片和文字之间必须有固定的间距,因此当我更改文字的长度时,图片与文字之间的距离仍应保持固定的间距。
而且我还试图在图像上添加一个功能(如果单击它,则会出现指向网站d的链接)
这是我要复制的内容
An example in image for what I am saying
到目前为止,这是我的代码(我已经尝试了一些方法,但是它们不起作用)
var svgContainer = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
var g = d3.select("svg") .append("g")
var rectangle = g.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 300)
.attr("height", 200)
.style("fill","pink");
var text = g.append("text")
.attr("x",150)
.attr("y",100)
.attr("text-anchor","middle")
.text('Nam oc cho')
var img = g.append("image")
.attr("x",200)
.attr("y",85)
.attr("href","firefox.jpg")
.attr("height","20px")
.attr("width","20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
由于文本是用text-anchor编写的:中间的长度是150之前的一半,一半是150之后的。因此,我们只需要将其长度的一半加到它的x位置即可找到它的末端。
var svgContainer = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500);
var g = d3.select("svg") .append("g")
var rectangle = g.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 300)
.attr("height", 200)
.style("fill","pink");
var text = g.append("text")
.attr("x",150)
.attr("y",100)
.attr("text-anchor","middle")
.text('Nam oc cho')
var img = g.append("image")
.attr("x",150 + text.node().getComputedTextLength () / 2)
.attr("y",85)
.attr("href","https://cnet2.cbsistatic.com/img/0ssO7VfSYSEzbQVQ6uK6FYamQx4=/940x0/2014/06/13/c582d2aa-092e-4d29-a616-a1e5c9403b36/firefox-logo-2014-vertical-4sts.jpg")
.attr("height","20px")
.attr("width","20px")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>