Canvas Rollover Shapes
For more details see https://northcoder.com/post/drawing-shapes-on-an-html-image-wit/
by northcoder
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
<img id="source" alt="taverna" style="display: none;"
src="https://user-images.githubusercontent.com/56733719/141156687-8bbb9eec-4752-4169-b108-50e397e4a8b7.png">
<div id="container" style="margin: auto; border:1px solid #d3d3d3;">
<canvas id="canvas"></canvas>
</div>
<div class="targets">
<div style="padding: 10px;">
<span class="mousetgt" data-idx="0">
<a id="lions_link"
data-idx="0"
href="#">[details]</a>
</span>
<span class="mousetgt" data-idx="0">This is area one</span>
</div>
<div style="padding: 10px;">
<span class="mousetgt" data-idx="1">
<a id="lions_link"
data-idx="1"
href="#">[details]</a>
</span>
<span class="mousetgt" data-idx="1">This is area two</span>
</div>
</div>
</body>
</html>
CSS
.targets {
text-align: center;
padding: 10px;
}
JavaScript
window.onload = function() {
// load image onto canvas
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('source');
const container = document.getElementById('container');
container.style.width = '' + (img.naturalWidth + 2) + 'px';
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 1, 1);
// get canvas related references
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
let fillStyle = 'rgba(255, 255, 255, 0.6)';
let strokeStyle = 'red';
// an array of objects that define different shapes:
var shapes = [];
// for testing:
shapes.push( {
idx: 0,
type: 'circle',
x: 220,
y: 130,
r: 65
} );
shapes.push( {
idx: 1,
type: 'rect',
x: 420,
y: 330,
width: 145,
height: 115
} );
// which shape is the mouse currently inside:
var currShape = -1;
// listen for global mouse events
canvas.onmousemove = myMove;
canvas.onclick = myClick;
$( ".mousetgt" ).on( "mouseenter", function() {
let idx = $( this ).attr("data-idx");
clear();
drawShape(shapes[idx]);
});
$( ".mousetgt" ).on( "mouseleave", function() {
clear();
});
// draw a single rect
function drawRect(r) {
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.beginPath();
ctx.rect(r.x, r.y, r.width, r.height);
ctx.stroke();
ctx.fill();
}
// draw a single circle
function drawCircle(c) {
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.beginPath();
ctx.arc(c.x, c.y, c.r, 0, Math.PI * 2);
ctx.stroke();
ctx.fill();
}
// draw the shape's index number in the shape,
// for easier visual identification:
function drawNumber(i, x, y) {
ctx.font="12px Arial";
ctx.textAlign="center";
ctx.textBaseline = "middle";
ctx.fillStyle = "rgba(255, 0, 0, 0.6)";
ctx.fillText(i+1, x, y);
}
//...