Skip to content

Instantly share code, notes, and snippets.

@1wheel
Last active March 2, 2018 11:53
Show Gist options
  • Save 1wheel/5d32ecb8a54b42f53646 to your computer and use it in GitHub Desktop.
Save 1wheel/5d32ecb8a54b42f53646 to your computer and use it in GitHub Desktop.
two line intersection
//creates new point
function P(x, y, color){
var rv = {x: x, y: y, color: color || 'black'}
rv.toString = function(){ return rv.x + ',' + rv.y }
return rv
}
//dist
//angle
//intersection between lines connect points [a, b] and [c, d]
function intersection(a, b, c, d){
var det = (a.x - b.x)*(c.y - d.y)
- (a.y - b.y)*(c.x - d.x),
l = a.x*b.y - a.y*b.x,
m = c.x*d.y - c.y*d.x,
ix = (l*(c.x - d.x) - m*(a.x - b.x))/det,
iy = (l*(c.y - d.y) - m*(a.y - b.y))/det,
i = P(ix, iy)
i.isIntersection = !(a.x < ix ^ ix < b.x)
&& !(c.x < ix ^ ix < d.x)
return i
}
function isLeft(a, b, c){
return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x) > 0
}
function lineXatY(l, y){
var a = l[0], b = l[1],
m = (a.y - b.y)/(a.x - b.x)
return (y - a.y + m*a.x)/m
}
function toPathStr(d){ return 'M' + d.join('L') }
function randString(len){
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
return d3.range(len).map(function(){
return alpha[Math.floor(Math.random()*alpha.length)]
}).join('')
}
function randColor(){
return 'rgb(' + [Math.random()*255, Math.random()*255, Math.random()*255].map(Math.round) + ')'
}
function clamp(min, d, max){
return Math.min(max, Math.max(min, d))
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path{
stroke: black;
}
.point{
fill: #ddd;
stroke: #aaa;
cursor: pointer;
}
</style>
<script src="/1wheel/raw/67b47524ed8ed829d021/d3-3.5.5.js"></script>
<script src="/1wheel/raw/67b47524ed8ed829d021/lodash-3.8.0.js"></script>
<script src='/1wheel/raw/1b6758978dc2d52d3a37/d3-jetpack.js'></script>
<script src='/1wheel/raw/1b6758978dc2d52d3a37/d3-starterkit.js'></script>
<script src='geometry.js'></script>
<script src='line-intersection.js'></script>
var r = 25
width = 960 - 2*r,
height = 500 - 2*r
var points = d3.range(4).map(function(d){
return P(width*Math.random(), height*Math.random())
})
var lines = [[points[0], points[1]], [points[2], points[3]]]
var drag = d3.behavior.drag()
.origin(ƒ())
.on('drag', function(d){
d.x = Math.max(0, Math.min(width, d3.event.x))
d.y = Math.max(0, Math.min(height, d3.event.y))
render()
})
var svg = d3.select('html')
.append('svg')
.attr({width: width + 2*r, height: height + 2*r})
.append('g')
.translate([r, r])
svg.dataAppend(points, 'circle.point')
.attr('r', r)
.call(drag)
svg.dataAppend(lines, 'path')
svg.append('circle.intersection')
.attr('r', 5)
function render(){
d3.selectAll('.point')
.translate(ƒ())
d3.selectAll('path')
.attr('d', toPathStr)
var i = intersection.apply(null, points)
d3.selectAll('.intersection')
.translate(i)
.style('fill', i.isIntersection ? 'red' : '#333')
}
render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment