block by jmuyskens 16961f08008ea0c7b4e00a9b8656e924

fresh block

Full Screen

Built with blockbuilder.org

forked from anonymous‘s block: fresh block

forked from anonymous‘s block: fresh block

forked from anonymous‘s block: fresh block

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    svg { width:100%; height: 100% }
    path { stroke: black; fill: none; }
  </style>
</head>

<body>
  <script>
    // Feel free to change or delete any of the code you see!
    var svg = d3.select("body").append("svg")
    var points = [
      {
        'anchor': [10, 10],
        'control': [70, 10]
      },
      {
        'anchor': [200, 200],
        'control': [140, 200]
      }
    ]
    function translate(arr) {
      return "translate(" + arr[0] + "," + arr[1] + ")";
    }
    
    function svgPath(points) {
      var path = 'M';
      points.forEach(function(d, i) {
        if (i == 0) {
          path += d.anchor[0] + ',' + d.anchor[1];
          path += ' C ' + d.control[0] + ',' + d.control[1];
        } else {
          path += ' ' + d.control[0] + ',' + d.control[1];
          path += ' ' + d.anchor[0] + ',' + d.anchor[1];
        }
      })
      return path;
    }
    
    var drag = d3.behavior.drag()
    	.on('drag', function(d, i) {
        console.log(i, points)
        point = [d3.event.x, d3.event.y];
        points[i].control = point;
        path.attr('d', svgPath(points));
        d3.select(this).attr('transform', 
                             translate(point));
      })
    
    var dragAnchors = d3.behavior.drag()
    	.on('drag', function(d, i) {
        console.log(i, points)
        point = [d3.event.x, d3.event.y];
        points[i].anchor = point;
        path.attr('d', svgPath(points));
        d3.select(this).attr('transform', 
                             translate(point));
      })
    
    
    var path = svg.append('path')
    	.attr('d', svgPath(points))

    var nodes = svg.selectAll('g.point')
    	.data(points)
    	.enter().append('g')
    	.attr('class', 'point');
    
    var anchors = nodes.append('circle')
    	.attr('r', 5)
    	.attr('transform', function(d) {
      	return translate(d.anchor)
    	}).call(dragAnchors);
   
    
    var controls = nodes.append('circle')
    	.attr('r', 5)
    	.attr('transform', function(d) {
	      return translate(d.control)
	    }).call(drag);
    

    console.log("you are now rocking with d3", d3);
  </script>
</body>