Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active September 19, 2024 23:09
Show Gist options
  • Save mbostock/f705fc55e6f26df29354 to your computer and use it in GitHub Desktop.
Save mbostock/f705fc55e6f26df29354 to your computer and use it in GitHub Desktop.
Line Drawing
license: gpl-3.0
redirect: https://observablehq.com/@d3/draw-me

Drag to draw a line!

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: none;
stroke: #000;
stroke-width: 3px;
stroke-linejoin: round;
stroke-linecap: round;
}
</style>
<svg width="960" height="500">
<rect fill="#fff" width="100%" height="100%"></rect>
</svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var line = d3.line()
.curve(d3.curveBasis);
var svg = d3.select("svg")
.call(d3.drag()
.container(function() { return this; })
.subject(function() { var p = [d3.event.x, d3.event.y]; return [p, p]; })
.on("start", dragstarted));
function dragstarted() {
var d = d3.event.subject,
active = svg.append("path").datum(d),
x0 = d3.event.x,
y0 = d3.event.y;
d3.event.on("drag", function() {
var x1 = d3.event.x,
y1 = d3.event.y,
dx = x1 - x0,
dy = y1 - y0;
if (dx * dx + dy * dy > 100) d.push([x0 = x1, y0 = y1]);
else d[d.length - 1] = [x1, y1];
active.attr("d", line);
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment