Skip to content

Instantly share code, notes, and snippets.

@mbostock

mbostock/.block Secret

Last active October 7, 2020 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/519d494035dd642e19eee4e242570114 to your computer and use it in GitHub Desktop.
Save mbostock/519d494035dd642e19eee4e242570114 to your computer and use it in GitHub Desktop.
redirect: https://observablehq.com/d/a214f3ade57f16cc
<!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