d3 triangle

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 = [],
    lineFunction = d3.svg.line()
        .x(function (d) {
            return d.x;
        })
        .y(function (d) {
            return d.y;
        }),
    path, circle, isDown = false, isClicking = false, m1, m2, count = 0; // firstClick = true,

svg.on('mousedown', function(){
   m1 = d3.mouse(this);
   isClicking = true;
   if(count < 2) {
       isClicking = true;   
       console.log('count', count);
       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('test');
       isClicking = false;
       count = 0; 
   }      
})
.on('mousemove', function(){
   m2 = d3.mouse(this);     
    if(isClicking) {
        //console.log('**path**', lineFunction(pathArray));
        pathArray[pathArray.length-1] = {'x': m2[0], 'y': m2[1]};
        if(pathArray.length == 3){            
            closePath();
        } else if(pathArray.length < 3){ 
            updatePath();
        }
    }
});
function updatePath(){
    if(!path){
        path = svg.append('path');  
    }    
    path.attr('d', lineFunction(pathArray)).attr('fill', 'none'); 
    drawCircle();
}
function closePath(){      
    path.attr('d', lineFunction(pathArray) + 'Z');
    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; });      
}