Get started with d3-drag CDN

BSD-3-Clause licensed

D3-drag: Draggable elements in D3.js visualizations.

Tags:
  • d3
  • d3-module
  • drag
  • behavior
  • interaction

Stable version

Copied!

How to start using d3-drag CDN


<!DOCTYPE html>
<html>
<head>
  <title>Get started with d3-drag CDN - cdnhub.io</title>
  <style>
    .drag-line path {
      fill: none;
      stroke: black;
      stroke-width: 1px;
      shape-rendering: crispEdges;
    }
  </style>
</head>
<body>
  <script src="https://d3js.org/d3.v6.min.js"></script>
  <script src="https://cdn.cdnhub.io/d3-drag/3.0.0/d3-drag.min.js"></script>
  <script>
    const svg = d3.select('body')
      .append('svg')
      .attr('width', 500)
      .attr('height', 500);

    const circle = svg.append('circle')
      .attr('cx', 250)
      .attr('cy', 250)
      .attr('r', 50)
      .call(d3.drag()
        .on('start', function() {
          drag = d3.event.sourceAppendedToG;
          dragging = true;
        })
        .on('drag', function() {
          d3.select(this).attr('cx', d3.event.x)
            .attr('cy', d3.event.y);
          if (drag) {
            drag.attr('cx', d3.event.x)
              .attr('cy', d3.event.y);
          }
        })
        .on('end', function() {
          if (!dragging) {
            d3.select(this).call(d3.drag()
              .on('start', null)
            );
          }
          dragging = false;
        })
      );

    const line = svg.append('path')
      .attr('class', 'drag-line')
      .attr('d', 'M0,0 L0,0');

    const dragline = d3.behavior.drag()
      .on('drag', function() {
        line.attr('d', 'M' + d3.event.sourceAppx + ',' + d3.event.sourceY + ' L' + d3.event.x + ',' + d3.event.y);
      });

    svg.call(dragline);
  </script>
</body>
</html>

All versions