Use Geometric.js to determine whether a point is to the left or right of a line.
To The Left, To The Right
This file contains 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 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/jeezy@1.13.0/lib/jeezy.min.js"></script> | |
<script src="https://unpkg.com/geometric@1.0.0/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