Reputation: 2122
I'm pretty new to d3 and fairly inexperienced with svg objects and I'm trying to place d3 generated circle elements on a page. I've followed several different tutorials and kinda mixed them all together and can't figure out why my current code doesn't work. html below;
<body>
<div id="svgDiv"></div>
<script src="~/Scripts/jQuery/jquery-1.10.2.min.js"></script>
<script src="~/scripts/d3/d3.min.js"></script>
<script src="~/scripts/App/test.js"></script>
</body>
And the javascript (test.js)
var windowWidth = $(window).width();
var windowLength = $(window).height();
var yPos = [50, 100, 150, 200, 250];
var base = d3.select("#svgDiv").append("svg")
.attr("width", windowWidth)
.attr("height", windowLength);
$(document).ready(function () {
windowWidth = $(window).width();
windowLength = $(window).height();
base.attr("width", windowWidth)
.attr("height", windowLength);
document.body.style.overflow = 'hidden';
});
$(window).resize(function () {
windowWidth = $(window).width();
windowLength = $(window).height();
base.attr("width", windowWidth)
.attr("height", windowLength);
});
$("div").click(function (e) {
base.selectAll("circle")
.data(yPos)
.enter()
.append("circle")
.attr("x", function (d, i) {
return yPos[i];
})
.attr("y", function (d, i) {
return yPos[i];
})
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 20)
.style("fill", "00ACCD");
console.log("click works");
});
So this should (and does) generate 5 svg circles on click at x and y = 50, 100, 150... 250 but all 5 circles are placed on top of each other in the top left of the page.
Any insight into this behaviour would be greatly appreciated, my primary language is C#.net and d3 really doesn't seem to be clicking with me at the moment.
Thanks in advance
Upvotes: 2
Views: 1999
Reputation: 30219
Just put an answer to the question. (@Gerardo has addressed it in the comments.)
Use attributes cx
and cy
to position the SVG circles, instead of x
and y
. (See Mike Bostock's circle tutorial) Here is the fix:
In the click event for this question, you'll see the circles as below, not on top of each other:
Upvotes: 2