Use Geometric.js to determine whether a point is to the left or right of a line.
Last active
December 20, 2018 17:13
-
-
Save HarryStevens/e6b53f48aff3a2bea1f99604cde1a99f to your computer and use it in GitHub Desktop.
To The Left, To The Right
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<style> | |
body { | |
margin: 0; | |
} | |
line { | |
stroke: #000; | |
} | |
polygon { | |
fill: none; | |
} | |
.left.active { | |
fill: steelblue; | |
} | |
.right.active { | |
fill: tomato; | |
} | |
</style> | |
</head> | |
<body> | |
<script src="https://d3js.org/d3-selection.v1.min.js"></script> | |
<script src="https://unpkg.com/[email protected]/lib/jeezy.min.js"></script> | |
<script src="https://unpkg.com/[email protected]/build/geometric.min.js"></script> | |
<script> | |
var width = window.innerWidth, height = window.innerHeight, halfWidth = width / 2; | |
var pointA = [jz.num.randBetween(halfWidth + 200, halfWidth), 0]; | |
var pointB = [jz.num.randBetween(halfWidth, halfWidth - 200), height]; | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
var line = svg.append("line") | |
.attr("x1", pointA[0]) | |
.attr("y1", pointA[1]) | |
.attr("x2", pointB[0]) | |
.attr("y2", pointB[1]); | |
var left = svg.append("polygon") | |
.attr("class", "left") | |
.attr("points", [[0, 0], [pointA], [pointB], [0, height]].join(" ")); | |
var right = svg.append("polygon") | |
.attr("class", "right") | |
.attr("points", [[width, 0], [pointA], [pointB], [width, height]].join(" ")); | |
svg.on("mousemove", _ => { | |
var p = [d3.event.pageX, d3.event.pageY]; | |
var leftOfLine = geometric.pointLeftofLine(p, [pointA, pointB]); | |
var rightOfLine = geometric.pointRightofLine(p, [pointA, pointB]); | |
left.classed("active", leftOfLine); | |
right.classed("active", rightOfLine); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment