-
-
Save mbostock/519d494035dd642e19eee4e242570114 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
redirect: https://observablehq.com/d/a214f3ade57f16cc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<svg width="960" height="500"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var svg = d3.select("svg"), | |
width = +svg.attr("width"), | |
height = +svg.attr("height"), | |
originX = width / 2, | |
originY = height / 2; | |
svg.selectAll("circle") | |
.data([{x: 0, y: 0}]) | |
.enter().append("circle") | |
.attr("cx", function(d) { return fromCartesianX(d.x); }) | |
.attr("cy", function(d) { return fromCartesianY(d.y); }) | |
.attr("r", 20) | |
.call(d3.drag() | |
.subject(function(d) { return {x: fromCartesianX(d.x), y: fromCartesianY(d.y)}; }) | |
.on("drag", dragged)); | |
function fromCartesianX(x) { | |
return originX + x; | |
} | |
function fromCartesianY(y) { | |
return originY - y; | |
} | |
function toCartesianX(x) { | |
return x - originX; | |
} | |
function toCartesianY(y) { | |
return -y + originY; | |
} | |
function dragged(d) { | |
d.x = toCartesianX(d3.event.x); | |
d.y = toCartesianY(d3.event.y); | |
d3.select(this).attr("cx", d3.event.x).attr("cy", d3.event.y); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment