D3 将文本附加到 SVG 矩形 [英] D3 Appending Text to a SVG Rectangle

查看:40
本文介绍了D3 将文本附加到 SVG 矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将 html 附加到 D3 中的矩形上,以便为我提供多行工具提示.底部是我如何添加一个矩形,这可能是问题的一部分.顶部是应该在我的世界中工作的代码.

I'm looking to append html onto a rectangle in D3 to give me a multiple line tooltip. The bottom part is how I'm adding a rectangle which may be part of the problem. The top is the code that should work in my world.

 newRect.().html(" <textArea font-family=Verdana font-size=20 fill=blue > Test " + "</br>" + "Test2 </textArea>");

将文本字段插入到 SVG 中,它只是不显示:
HTML:

Which does insert a text field into the SVG, it just doesn't display:
HTML:

<rect id="rectLabel" x="490" y="674" width="130" height="160" fill="red">
    <textarea fill="blue" font-size="20" font-family="Verdana"> Test </br>Test2 </textarea>
</rect>

我有一个运行以下内容的鼠标悬停功能:

I have a mouse over function which runs the following:

    newRect = svg.append("rect")
    .attr("x", xCor)
    .attr("y", yCor)
    .attr("width", 130)
    .attr("height", 160)
    .attr("fill", "red")
    .attr("id", "rectLabel");

我想我应该这样做,但它不起作用.它只是删除了我试图附加到的 g.node.

I think I should be doing this but it doesn't work. It just removes the g.node that I'm trying to append to.

    newRect = $(this).enter().append("rect")
    .attr("x", xCor)
    .attr("y", yCor)
    .attr("width", 130)
    .attr("height", 160)
    .attr("fill", "red")
    .attr("id", "rectLabel");

问题:为什么我的文字不显示?我试过 .html、.textArea.我想要一个多行标签,所以我认为 .text 不会正常工作?另外,我应该如何附加矩形?

Question: Why doesn't my text appear? Ive tried .html, .textArea. I want a multiple line label so I don't think .text will work correct? Also, how should I be appending the rectangle?

推荐答案

rect 不能包含 text 元素.而是使用文本和矩形的位置转换 g 元素,然后将矩形和文本附加到它:

A rect can't contain a text element. Instead transform a g element with the location of text and rectangle, then append both the rectangle and the text to it:

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

http://bl.ocks.org/mbostock/7341714

多行标签也有点棘手,你可能想看看这个包装功能.

Multi-line labels are also a little tricky, you might want to check out this wrap function.

这篇关于D3 将文本附加到 SVG 矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆