如何使用d3 js在SVG文件上创建带有文本的圆圈

how to create circles with text over svg file using d3 js?

本文关键字:文本 创建 d3 何使用 js 文件 SVG      更新时间:2023-09-26

我是d3 js的初学者。我有一个div,其中包含有svg文件的对象标记。
我需要在svg文件上创建文本圆圈,并使用d3 js绑定点击函数。
提前谢谢。下面是我的html代码:

<div class="span8 canvasDiv">
    <object data="img/floor.svg" type="image/svg+xml" id="floorCanvas"></object>
</div>

JS代码:

var svgContainer = d3.select("#floorCanvas");
var circle = svgContainer.append("circle")
                         .attr("cx", 30)
                         .attr("cy", 30)
                         .attr("r", 20);

你需要创建一个'g'标签,然后将圆圈和文本都附加到'g'上,因为你不能直接将文本附加到SVG形状上,所以像这样(未测试):

HTML:

 <div class="span8 canvasDiv">
        <object data="img/floor.svg" type="image/svg+xml" id="floorCanvas"></object>
        </div>

JS代码:

 var svgContainer = d3.select("#floorCanvas").append('svg').append('g').attr('id', 'circleWithText');
 var circleWithText = d3.select("#circleWithText");
 circleWithText .append("circle")
                .attr("cx", 30)
                .attr("cy", 30)
                .attr("r", 20);
 circleWithText.append('text')
                .attr('class', 'text')
                .attr("dx", "0")
                .attr("dy", "0")
                .text('what ever you want here');
CSS

.text{
    text-anchor: middle;
    color: steelblue;
    position:relative;
    font: 14px Calibri;
}

这几行