block by mbostock f705fc55e6f26df29354

Line Drawing

Full Screen

Drag to draw a line!

Updated Example →

index.html

<!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>