Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active December 20, 2018 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarryStevens/e6b53f48aff3a2bea1f99604cde1a99f to your computer and use it in GitHub Desktop.
Save HarryStevens/e6b53f48aff3a2bea1f99604cde1a99f to your computer and use it in GitHub Desktop.
To The Left, To The Right
license: gpl-3.0

Use Geometric.js to determine whether a point is to the left or right of a line.

<!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