使用d3.js单击圆形以矩形显示数据
我有几个包含人名的圆圈,我需要使用d3.js在矩形中单击圆圈来显示他们的信息 下面是我的剧本使用d3.js单击圆形以矩形显示数据,d3.js,D3.js,我有几个包含人名的圆圈,我需要使用d3.js在矩形中单击圆圈来显示他们的信息 下面是我的剧本 var width = 960, height = 500; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) d3.json("data.json", function (json) { /* Define the
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
d3.json("data.json", function (json) {
/* Define the data for the circles */
var elem = svg.selectAll("g myCircleText")
.data(json.nodes)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.attr("transform", function (d) { return "translate(" + d.x + ",80)" })
/*Create the circle for each block */
var circle = elemEnter.append("circle")
.attr("r", function (d) { return d.r })
.attr("stroke", "black")
.attr("fill", "white")
.on("click", function () {
var s = svg
.selectAll("circle");
s
.append("rect")
.attr("x", 100)
.attr("y", 200)
.attr("width", 200)
.attr("width", 200)
.style("fill", "red");
});
/* Create the text for each block */
elemEnter.append("text")
.attr("dx", function (d) { return -20 })
.text(function (d) { return d.label })
})
below is the json file:
{"nodes":[
{"x":80, "r":40, "label":"Sam","info":"Developer"},
{"x":200, "r":60, "label":"Pam","info":"Programmer"},
{"x":380, "r":80, "label":"Ram","info":"Architect"}
]}
圆圈是用名字画的,但当我点击圆圈时,什么都没有发生
请帮忙
谢谢你的onclick函数有两个问题。首先,第二次设置宽度而不是高度:
.attr("width", 200)
.attr("width", 200)
第二,将矩形附加到圆上:
var s = svg.selectAll("circle");
s.append("rect")
这对于svg无效:
<circle r="60" stroke="black" fill="white">
<rect></rect>
</circle>
嗨,亚当,非常感谢你的回复,它奏效了:)。我还试着用那个人的矩形显示数据。所以我尝试了以下方法:svg.append(“rect”).attr(“x”,100).attr(“y”,200).attr(“width”,200).attr(“height”,200).style(“fill”,“red”).text(“text”,函数(d){return d.info});但它并没有在矩形上显示文本,也可以在矩形中同时显示图像和数据,比如左侧的人物图像和右侧的信息。再次感谢您的帮助。如果亚当的答案有帮助,那么您应该继续接受它。我如何获得与该圆圈相关的数据并将其显示在矩形中?这就是问题所在。
.on("click", function () {
svg.append("rect")
.attr("x", 100)
.attr("y", 200)
.attr("width", 200)
.attr("height", 200)
.style("fill", "red");
});