关于d3.js的添加文本的问题,最近在利用d3开发一款标注工具,今天遇到一个小问题,就是对标注好的矩形或者是点旁边要给添加一个文本,从开始做就一直在尝试,但是始终是显示不出来。
这是我使用的d3版本
"d3": "^7.0.0",
画布中的元素是一个矩形,以下是生成矩形的代码
svg.append("g")
.append("rect") //添加一个矩形
.attr("x",x0)
.attr("y",y0)
.attr("width",width1)
.attr("height",height1)
.attr("stroke", "yellow")
.attr("fill", "yellow")
.attr("fill-opacity", 0.1)
刚开始的思路很简单,就是接着在这串代码后边跟着写我要加的文本
svg.append("g")
.append("rect") //添加一个矩形
.attr("x",x0)
.attr("y",y0)
.attr("width",width1)
.attr("height",height1)
.attr("stroke", "yellow")
.attr("fill", "yellow")
.attr("fill-opacity", 0.1)
.append("title")
.text("矩形1")
上述代码只是我尝试的一种,但是不管怎么写画布上始终没有,打开f12审核元素的时候,文本标签是存在的,后来在网上找了找相似的问题,有一种说法是你要添加的文本不能这样写,文本元素也是独立的,以下是完整代码
svg.append("g")
.append("rect") //添加一个矩形
.attr("x",x0)
.attr("y",y0)
.attr("width",width1)
.attr("height",height1)
.attr("stroke", "yellow")
.attr("fill", "yellow")
.attr("fill-opacity", 0.1)
svg.append("g")
.append('text')
.attr("x",x0+30)
.attr("y",y0)
.style('font-weight', 500)
.style('font-family', 'Arial')
.style('fill', 'red')
.text("矩形1")
x和y是你用来控制文本元素显示的位置,其他的都是字体颜色,大小,字号什么的,text是你想要显示的文本元素内容,最终画布上内容是呈现了,要说的就是这么多。