d3 slope ray

by Amanda Williamson

JavaScript

var svg = d3.select('body')
            .append('svg')
            .attr({'width': 500, 'height': 500})
            .style({'border': 'solid 1px black'});

var m, m1, m2, line, isDown = false, firstClick = true, pathArray = [], pathArray1 = [],
    x1, y1, x2, y2, slope, isLeft;

var lineFunction = d3.svg.line()
                    .x(function(d) { return d.x; })
                    .y(function(d) { return d.y; })
                    .interpolate("linear");

// formula for the slope
function getSlope(x1, y1, x2, y2) {
    return ((y2 - y1) / (x2 - x1));
}
     
function getY(anchorX, anchorY, mouseX, mouseY, isLeft) {
    m = getSlope(anchorX, anchorY, mouseX, mouseY),
        viewportLeft = 0,
        viewportRight = 500;
    return m * ((isLeft ? viewportLeft : viewportRight) - anchorX) + anchorY;
}

svg.on('mousedown', mousedown);
function mousedown() {
    isDown = !isDown;
    m1 = d3.mouse(this);
    pathArray = [ { x: m1[0], y: m1[1] } ];
    if(firstClick) {
         point = svg.append('circle')
                    .attr("class", "point")
                    .attr("cx", m1[0])
                    .attr("cy", m1[1])
                    .attr("r", 5);
    line = svg.append('path')
            .attr('d', lineFunction(pathArray))
            .attr({'stroke': 'purple', 'stroke-width': 5, 'fill': 'none'});
    }
    firstClick = !firstClick;
}

svg.on('mousemove', mousemove);
function mousemove() {
    m2 = d3.mouse(this);         
    var equalsZero = false, isPosInf, isNegInf, equalsInfinity;  
    
    if(isDown){
        if((m2[0] - m1[0]) > 0) {
            isLeft = false;
            pathArray[1] = { x: 500, y: getY(m1[0], m1[1], m2[0], m2[1], isLeft) };
        } else if((m2[0] - m1[0]) < 0) {
            isLeft = true;
            pathArray[1] = { x: 0, y: getY(m1[0], m1[1], m2[0], m2[1], isLeft) };
        } else if((m2[0] - m1[0]) === 0) {
            equalsZero = true; 
        }    
        
        if(equalsZero) {
            equalsInfinity =...