我一直在尝试使用D3.js创建一个罐子,其中的圆圈(代表感觉到的情绪)彼此堆叠。不幸的是,它们没有堆叠在一起,它们只是重叠。
这是我的代码:
var circle_counter = 0; // Global variable
var level_counter = 0; // Global variable
var circles = d3
.select("svg")
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d) {
if (circle_counter < 6) {
d.cx = 62.5 + circle_counter * 45;
circle_counter++;
return d.cx;
} else {
level_counter++;
circle_counter = 0;
d.cx = 62.5 + circle_counter * 45;
circle_counter++;
return d.cx;
}
})
.attr("cy", function(d) {
if (level_counter == 0) {
return (d.cy = 320);
} else {
return (d.cy = 320 - level_counter * 20);
}
})
.attr("r", 20)
.attr("fill", function(d) {
if (d.main_emotion == "anger") {
return "red";
} else if (d.main_emotion == "disgust") {
return "green";
} else if (d.main_emotion == "fear") {
return "black";
} else if (d.main_emotion == "happiness") {
return "yellow";
} else if (d.main_emotion == "sadness") {
return "blue";
} else {
return "orange";
}
})
.attr("fill-opacity", 0.5)
.attr("stroke", "white")
.attr("stroke-width", 3);
这就是我要得到的:
这是我要实现的目标:
如何实现这一目标?
谢谢。
编辑:我忘了提到我感觉'circles_counter'和/或'level_counter'变量以某种方式混杂在一起,但是在解决这个问题的无数尝试之后,我对我的逻辑怎么了。
答案 0 :(得分:0)
我不确定这是否是正确的方法,但我可以实现。在使用此代码之前,请仔细阅读D3提供的资源,并检查是否有更好的方法。
var data = [
{main_emotion: 'sadness'},
{main_emotion: 'happiness'},
{main_emotion: 'fear'},
{main_emotion: 'anger'},
{main_emotion: 'disgust'},
]
var dataSet = [];
for(let i = 0, len = data.length; i < len; i += 1) {
for( let j = 0, len1 = data.length; j < len1; j += 1) {
let newDataSet = {};
const cx = 60 + (j * 45);
const cy = 320 - (i * 45);
newDataSet = {
...data[j],
cx: cx,
cy: cy,
}
dataSet.push(newDataSet);
}
}
var circles = d3
.select("svg")
.selectAll("circle")
.data(dataSet)
.enter()
.append("circle")
.attr("cx", function(d) {
return d.cx;
})
.attr("cy", function(d) {
return d.cy;
})
.attr("r", 20)
.attr("fill", function(d) {
if (d.main_emotion == "anger") {
return "red";
} else if (d.main_emotion == "disgust") {
return "green";
} else if (d.main_emotion == "fear") {
return "black";
} else if (d.main_emotion == "happiness") {
return "yellow";
} else if (d.main_emotion == "sadness") {
return "blue";
} else {
return "orange";
}
})
.attr("fill-opacity", 0.5)
.attr("stroke", "white")
.attr("stroke-width", 3)
</script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body {
background: #999;
}
</style>
<svg width=400 height=400></svg>