d3 triangle - drag and resize

old - closePath() new - interpolate('linear-closed');

by Amanda Williamson

CSS

svg {
    border: solid 1px black;
}

path {
    stroke-width: 5;
    stroke: purple;
    fill: mediumorchid;    
}

JavaScript

var svg = d3.select("body").append("svg").attr({ width: 500, height: 500 }),
    data = [], pathArray = [], path, circle, isDown = false, isClicking = false, m1, m2, count = 0,
    lineFunction = d3.svg.line()
        .x(function (d) { return d.x; })
        .y(function (d) { return d.y; })
        .interpolate('linear-closed');

svg.on('mousedown', function(){
   m1 = d3.mouse(this);
   isClicking = true;
   //console.log('count', count);
   if(count < 2) {
       isClicking = true;       
       if (count === 0) {
            //console.log('if');
            pathArray = [{ 'x':  m1[0], 'y': m1[1] }, { 'x':  m1[0], 'y': m1[1] }];
            updatePath(); 
        } else { 
            //console.log('else if');
            pathArray[pathArray.length] = { 'x':  m2[0], 'y': m2[1] };           
        }
       count++;
   } else {
       console.log('else');
       isClicking = false;
       path.call(dragP);
       d3.selectAll('circle').call(dragC);
   }    
})
.on('mousemove', function(){
   m2 = d3.mouse(this);     
    if(isClicking) {
        //drawCircle();
        pathArray[pathArray.length-1] = {'x': m2[0], 'y': m2[1]}; 
        updatePath();
    }
});
function updatePath(){
    if(!path){
        path = svg.append('path');  
    }    
    path.attr('d', lineFunction(pathArray)).attr('fill', 'none');
    drawCircle();
}
function drawCircle(){
    circle = svg.selectAll('circle').data(pathArray);    
    circle.enter().append('circle').attr('r', 10); 
    circle.attr('cx', function(d) { return d.x; })
          .attr('cy', function(d) { return d.y; });      
}
function updateCircle(){        
    circle.attr('cx', function(d) { return d.x; })
          .attr('cy', function(d) { return d.y; });     
}

var dragP = d3.behavior.drag().on('drag', dragPath), 
    dragC = d3.behavior.drag().on('drag', dragCircle);

function dragPath(dataSource) {
    //console.log('dragPath');
    var e = d3.event;
    pathArray.forEach(function(datum, index){
       ...