以下是代码:
//Circle Data Set
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];
//Create the SVG Viewport
var svgContainer = d3.select("#svgContainer")
.attr("width",200)
.attr("height",200);
//Add the SVG Text Element to the svgContainer
var text = svgContainer.selectAll("text")
.data(circleData)
.enter()
.append("text");
var circles = svgContainer.selectAll("circle")
.data(circleData)
.enter()
.append("circle")
.attr("cx", function(d) {return d.cx})
.attr("cy", function(d) {return d.cy})
.attr("r", function(d) {return d.radius})
.attr("fill", function(d) {return d.color})
//Add SVG Text Element Attributes
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
http://jsfiddle.net/kindlychung/jrsxLfpg/1/
似乎d3总是首先渲染文本,这意味着文本部分隐藏在圆圈后面:
<svg id="svgContainer" width="200" height="200">
<text x="20" y="20" font-family="sans-serif" font-size="20px" fill="red">( 20, 20 )</text>
<text x="70" y="70" font-family="sans-serif" font-size="20px" fill="red">( 70, 70 )</text>
<circle cx="20" cy="20" r="20" fill="green"></circle>
<circle cx="70" cy="70" r="20" fill="purple"></circle></svg>
我该如何调整?
答案 0 :(得分:2)
您需要在绘制圆圈之后绘制文本节点。
//Circle Data Set
var circleData = [
{ "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
{ "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];
//Create the SVG Viewport
var svgContainer = d3.select("#svgContainer")
.attr("width",200)
.attr("height",200);
// draw your circles and any other graphic elements first!
var circles = svgContainer.selectAll("circle")
.data(circleData)
.enter()
.append("circle")
.attr("cx", function(d) {return d.cx})
.attr("cy", function(d) {return d.cy})
.attr("r", function(d) {return d.radius})
.attr("fill", function(d) {return d.color})
// These will now be appended AFTER the circles
// When you use `append` it will add text nodes to end
// of svgContainer
var text = svgContainer.selectAll("text")
.data(circleData)
.enter()
.append("text");
// Here you are editing the pre-existing `text` nodes that you added above.
// Note that you don't use `append` here.
// Instead, you are modifying the d3 selection stored in `text`
var textLabels = text
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.text( function (d) { return "( " + d.cx + ", " + d.cy +" )"; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
以下是您的代码的编辑版本: http://jsfiddle.net/jrsxLfpg/2/