block by pnavarrc 5190856

Example of Drag Behavior in D3

Full Screen

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Drag Behavior Demo</title>
  </head>
    <script src="//d3js.org/d3.v3.min.js"></script>
  <body>

  <script type="text/javascript">

  var width = 600,
    height = 600,
    div = d3.select('body').append('div'),
    svg = div.append('svg'),
    bar = svg.append('rect'),
    drag = d3.behavior.drag();
 
    svg.attr('width',  width)
       .attr('height', height);
 
    // This function is called on drag
    function move(d) {
        var bar = d3.select(this);
        // Update the position of the bar by adding the drag distance in each coordinate
        bar.attr('x', parseInt(bar.attr('x'), 10) + d3.event.dx)
           .attr('y', parseInt(bar.attr('y'), 10) + d3.event.dy);
    }
 
    drag.origin(Object)
        .on('drag', move);
 
    bar = svg.append('rect'),
    bar.attr('x', (width - 200) / 2)
       .attr('y', (height - 200) / 2)
       .attr('width', 200)
       .attr('height', 200)
       .attr('fill', '#98CFEA')
       .call(drag);

  </script>
  </body>
</html>