I am drawing a node (circle) and trying to zoom it in and out using D3 Javascript. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample2</title>
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
</style>
</head>
<body>
<script type="text/javascript" src="d3.v3.js"></script>
<script>
var width = 1000;//960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
//Draw the Circle
var circle = svg.append("circle");
force
.nodes(d3.values(circle))
.start();
var resourceNode = svg.selectAll(".node")
.data(circle)
.enter().append("g")
.attr("class", "node")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.style("fill", function(d) { return color(2); })
.attr("r", 10)
.call(force.drag);
resourceNode.append("circle");
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 20);
}
function mouseout() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 10);
}
force.on("tick", function() {
resourceNode.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
resourceNode.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
</script>
</body>
</html>
In the code above, you may notice that I added the two functions: mouseover
and mouseout
. These two functions are for zooming in and out the node. I could manage to zoom the node in and out as soon as I moved the mouse over the node. My problem is: the node freezes in one position at the top left of the canvas and do not move anymore. If I delete the codes that are related to the zooming functions, I will be able to move the node anywhere I want. Could anyone please help me solve this problem? The zooming functions are OK but the node does not move anymore. It will move when I delete the zooming functions. I do not know what the problem is. Your assistance would be very much appreciated.
In your code, you're only controlling the positions of the g
elements through the force layout, not of the circle. You shouldn't really pass SVG elements as data to force layout or to D3 in general -- it will work technically, but almost certainly won't do what you want.
I've modified your example to do what you want here . Note that I've added actual data to pass to force layout and .data()
and draw elements according to that. The circle
elements are now attached to the g
elements as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.