如何使用d3.js根据数据确定SVG形状 [英] How to determine a SVG shape based off of data using d3.js
问题描述
This is related to an earlier question that I asked earlier: How to add filled sections to SVG circles using d3.js
这一次,我想根据人是女性还是男性来创建形状.如果此人是女性,我想创建一个圈子.如果我创建的人是男性,则我想创建一个正方形.
This time, I want to create a shape depending on if the person is a female or male. If the person is a female, I want to create a circle. If the person I create is a male, I want to create a square.
到目前为止,我可以创建两个形状,但是我不知道如何调用函数来确定我想要的形状.
So far, I'm able to create both shapes, but I don't know how to call a function to determine which shape I want.
这是我的小提琴: https://jsfiddle.net/g8wLtrc9/
我小提琴中的这段代码是我试图确定形状的尝试:
This block of code from my fiddle is my attempt to determine my shape:
var shapes = node.append("g")
shapes.enter()
.append('g')
.each(function(d){
var g = node.select(this);
if(d.sex === 'f'){
g.attr("class", "circle")
g.append("circle")
g.attr("r", function(d){
return d.type == "family" ? family_radius : 40;
})
}
else{
g.attr("class", "rect")
g.append("rect")
g.attr("width", 80)
g.attr("height", 80)
g.attr("x", -40)
g.attr("y", -40)
}
})
.attr("fill",function(d,i){
if(d.type == "family"){return "white"}
else{return "url(#my_image" + i + ")"}})
.attr("stroke", function(d){
if (d.type == "family"){return "gold";
} else { if(d.sex == "m"){return "blue"
} else { return "#ed1851"}}})
.attr("stroke-width","4px")
.on("mouseover", function(d){
if(d.type !== "family"){
t_text = "<strong>" + titleCase(d.name) + "</strong><br>Age: " + d.age
if(d.relationship !== undefined){
t_text += "<br>Relationship: " + d.relationship}
tooltip.html(t_text)
return tooltip.style("visibility", "visible");
} })
.on("mousemove", function(){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");})
.on("click", function(d){return details(d);});
推荐答案
我尝试过删除外部圆并仅将正方形用于鼠标悬停事件.现在它是一个完全透明的rgba(0,0,0,0)
"hitbox".也防止了小型家庭圈子与d.sex === 'f' || d.type === 'family'
I've tried by removing the outer circle and using the square only for mouseover events. It is a completely transparent rgba(0,0,0,0)
"hitbox" now. Also prevented the small family circles from becoming squares with d.sex === 'f' || d.type === 'family'
饼图/正方形切片足以绘制完整形状,您已经成功地做到了.我认为您应该尝试在较小的部分上应用笔触/填充选项,并将悬停事件留在透明的较大框中,这样您就无需重复应用它. (当然,直到您希望这些较小的部分触发单独的事件为止)
The pie/square slices are enough to draw the full shape, you have done that successfully. I think you should try to apply the stroke/fill options on the small portions and leave the hover events to a transparent larger box so you don't need to apply it repetitively. (Until, of course, you want these smaller sections to fire separate events)
到目前为止,这里是您对JSFiddle进行的 https://jsfiddle.net/wa30rgb2/1/
Here's your JSFiddle edited so far: https://jsfiddle.net/wa30rgb2/1/
这篇关于如何使用d3.js根据数据确定SVG形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!