d3 - circle from dataset

by Amanda Williamson

CSS

.circle {
    fill: lightgreen;
    stroke: green;    
    stroke-width: 5px;
}

.point {
    fill: black;
}

JavaScript

var circle, data = [], theData, isDown = false, isDragging = false, m1, m2;

var svg = d3.select("body").append("svg").attr('width', 500).attr('height', 500)
    .style('border', 'solid 1px purple')
    .on("mousedown", mousedown)
    .on("mousemove", mousemove);

var dragC = d3.behavior.drag().on('dragstart', dragStart).on('dragend', dragEnd).on('drag', dragCircle);
var dragP = d3.behavior.drag().on('dragstart', dragStart).on('dragend', dragEnd).on('drag', dragPoint);

function mousedown() {
   m1 = d3.mouse(this);
   if (!isDown) {
        if(!isDragging){
            theData = { x1: m1[0], y1: m1[1], x2: m2[0], y2: m2[1] };
            data.push(theData);
            updateCircle();
        }
   } else {
      console.log('test');
      isDragging = true;
      circle.call(dragC);
   }
    isDown = !isDown;
}

function mousemove() {
    m2 = d3.mouse(this);
    if (isDown && !isDragging) {
        for(var i = 0; i < data.length; i++){
            if (data[i] === theData) {
                data[i].x2 = m2[0];
                data[i].y2 = m2[1];
            }
        } 
        updateCircle();
    }
}

function getRadius(x1, y1, x2, y2) {
    return Math.sqrt((Math.pow(x2 - x1, 2) + (Math.pow(y2 - y1, 2))));
}

function updateCircle() {
    circle = svg.selectAll('.circle').data(data);     
    circle.enter().append('circle').attr('class', 'circle').call(dragC);    
    circle.attr('cx', function (d) { return d.x1; })
          .attr('cy', function (d) { return d.y1; })
          .attr( 'r', function (d) { return getRadius(d.x1, d.y1, d.x2, d.y2); });
    
    point = svg.selectAll('.point').data(data);
    point.enter().append('circle')
         .attr('class', 'point')
         .attr('r', 5)
         .call(dragP);
    point.attr('cx', function (d) { return d.x2; })    
         .attr('cy', function (d) { return d.y2; });
}

function dragStart(d){
    isDown = false;
    isDragging = true;
}

function dragEnd(d){
    isDown = isDragging = false;    
}   ...