JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<p id="results">Move mouse in/out of triangle</p>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
}
#canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var $results = $("#results");
// create an object holding all polygon points
var triangle = [{
x: 100,
y: 50
}, {
x: 150,
y: 100
}, {
x: 50,
y: 100
}];
// draw the polygon
define(triangle);
ctx.fill();
// define the polygon
function define(polygon) {
ctx.beginPath();
ctx.moveTo(polygon[0].x, polygon[0].y);
for (var i = 1; i < polygon.length; i++) {
ctx.lineTo(polygon[i].x, polygon[i].y);
}
ctx.closePath();
}
function hitTest(polygon) {
// redefine the polygon
// (necessary to isPointInPath to work
define(polygon);
// ask isPointInPath to hit test the mouse position
// against the current path
return (ctx.isPointInPath(mouseX, mouseY));
}
function handleMouseMove(e) {
e.preventDefault();
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// check if the mouse is inside the polygon
var isInside = hitTest(triangle);
if (isInside) {
$results.text("Mouse is inside the Triangle");
} else {
$results.text("Outside");
}
}
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});