d3 extended ray
by Amanda Williamson
JavaScript
var w = 500, h = 500;
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 = w;
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){
line = svg.append('path')
.attr('d', lineFunction(pathArray))
.attr({'stroke': 'gold', 'stroke-width': 5, 'fill': 'none'});
}
firstClick = !firstClick;
}
svg.on('mousemove', mousemove);
function mousemove() {
m2 = d3.mouse(this);
if (isDown) {
pathArray1 = [{x: m1[0], y: m1[1]},
{x: 0, y: getY(m1[0], m1[1], m2[0], m2[1], true) },
{x: w, y: getY(m1[0], m1[1], m2[0], m2[1], false)}];
for(var i = 0; i < pathArray1.length; i++){
if(pathArray1[i].y === Number.POSITIVE_INFINITY){
pathArray1[i].x = m2[0];
pathArray1[i].y = 0;
}
else if(pathArray1[i].y === Number.NEGATIVE_INFINITY){
pathArray1[i].x = m2[0];
pathArray1[i].y = h;
}
}
line.attr('d', lineFunction(pathArray1));
}
}
/*
if (pathArray1[i].y > w) {
...