As a newbie to d3 and JavaScript, I'm facing an error that is beyond my current knowledge. I have successfully generated 6 circles using a 2D array and implemented a function to increment their x and y positions by 1 in each call of a timer. However, instead of updating the positions of the initial 6 circles, the timer keeps creating an infinite loop of "NaN" circles. Below is the code snippet I am using:
<body>
<div id="svgDiv"></div>
<script src="~/scripts/d3/d3.min.js"></script>
<script src="~/scripts/App/test.js"></script>
</body>
and the JavaScript part:
var windowWidth = window.innerWidth;
var windowLength = window.innerHeight;
var pos =
[[50, 40],
[100, 80],
[150, 120],
[200, 160],
[250, 200],
[300, 240]];
var base = d3.select("#svgDiv").append("svg")
.attr("width", windowWidth)
.attr("height", windowLength);
function initSetup() {
windowWidth = window.innerWidth;
windowLength = window.innerHeight;
base.attr("width", windowWidth)
.attr("height", windowLength);
document.body.style.overflow = 'hidden';
}
window.onload = initSetup;
function windowResize() {
windowWidth = window.innerWidth;
windowLength = window.innerHeight;
base.attr("width", windowWidth)
.attr("height", windowLength);
};
window.addEventListener("resize", windowResize);
function svgDivClick() {
base.selectAll("circle")
.data(pos)
.enter()
.append("circle")
.attr("cx", function (d, i) {
return pos[i][0];
})
.attr("cy", function (d, i) {
return pos[i][1];
})
.attr("r", 0)
.style("fill", "00ACCD")
.transition()
.attr("r", 20)
.style("fill", "00ACCD")
.duration(500);
base.exit().transition()
.attr("r", 0)
.remove();
console.log("click works");
d3.timer(animate);
};
document.getElementById("svgDiv").addEventListener("click", svgDivClick);
function animate() {
base.selectAll("circle")
.data("circle", function (d) { return d; })
.enter()
.append("circle")
.attr("cx", function (d, i) {
return d.cx + 1;
})
.attr("cy", function (d, i) {
return d.cy + 1;
});
base.exit().transition()
.attr("r", 0)
.remove();
};
My ultimate aim is to make the circles move randomly, but currently, I'm focusing on managing their positions. Note: The error occurs in the animate function.
I'd appreciate any insights or guidance on this issue. Thank you in advance!