JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<h3>This will not work in IE (use Chrome/FF)</h3>
<hr>
<h4>Move mouse over any arc</h4>
<h4>When mouse is over arc, that color rect will appear</h4>
<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 context = canvas.getContext("2d");
context.lineWidth = 15;
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var PI2 = Math.PI * 2;
// create some test data objects
var arcs = [];
//outer arcs
arcs.push({
cx: 100,
cy: 100,
radius: 75,
start: 0,
end: PI2 * .33,
color: "red"
});
arcs.push({
cx: 100,
cy: 100,
radius: 75,
start: PI2 * .33,
end: PI2 * .66,
color: "green"
});
arcs.push({
cx: 100,
cy: 100,
radius: 75,
start: PI2 * .66,
end: PI2,
color: "blue"
});
// inner arcs
arcs.push({
cx: 100,
cy: 100,
radius: 45,
start: 0,
end: PI2 * .55,
color: "purple"
});
arcs.push({
cx: 100,
cy: 100,
radius: 45,
start: PI2 * .55,
end: PI2 * .75,
color: "orange"
});
arcs.push({
cx: 100,
cy: 100,
radius: 45,
start: PI2 * .75,
end: PI2,
color: "maroon"
});
// visibly draw all arcs
for (var i = 0; i < arcs.length; i++) {
defineArc(arcs[i]);
context.strokeStyle = arcs[i].color;
context.stroke();
}
// define BUT NOT VISIBLY DRAW an arc
function defineArc(arc) {
context.beginPath();
context.arc(arc.cx, arc.cy, arc.radius, arc.start, arc.end);
}
// handle mousemove events
function handleMouseMove(e) {
// get mouse position
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);
// reset the results box to invisible
context.clearRect(225, 30, 20, 20);
// hit-test each arc
for (var i = 0; i < arcs.length; i++) {
// define one arc
defineArc(arcs[i]);
// test that one arc
// if "hit" fill the results box with that arc's color
if (context.isPointInStroke(mouseX, mouseY)) {
context.fillStyle = arcs[i].color;
context.fillRect(225, 30, 20, 20);
return;
}
}
}
// listen...