Skip to content

Instantly share code, notes, and snippets.

Last active June 17, 2023 08:35
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Line Drawing
license: gpl-3.0

Drag to draw a line!

<!DOCTYPE html>
<meta charset="utf-8">
path {
fill: none;
stroke: #000;
stroke-width: 3px;
stroke-linejoin: round;
stroke-linecap: round;
<svg width="960" height="500">
<rect fill="#fff" width="100%" height="100%"></rect>
<script src="//"></script>
var line = d3.line()
var svg ="svg")
.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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment