JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="450" height="450"></canvas>
JavaScript
$(document).ready(function () {
//Canvas stuff
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
canvas.style.left = "0px";
canvas.style.top = "0px";
canvas.style.position = "absolute";
//Lets paint the canvas now
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = "black";
ctx.strokeRect(0, 0, w, h);
// Set all Rectangles, Draw
var rects = [{
x: 0,
y: 0,
width: 150,
height: 150
}, {
x: 150,
y: 0,
width: 150,
height: 150
}, {
x: 300,
y: 0,
width: 150,
height: 150
}, {
x: 0,
y: 150,
width: 150,
height: 150
}, {
x: 150,
y: 150,
width: 150,
height: 150
}, {
x: 300,
y: 150,
width: 150,
height: 150
}, {
x: 0,
y: 300,
width: 150,
height: 150
}, {
x: 150,
y: 300,
width: 150,
height: 150
}, {
x: 300,
y: 300,
width: 150,
height: 150
}];
for (i = 0; i < 9; i++) {
ctx.rect(rects[i].x, rects[i].y, 150, 150);
ctx.stroke();
}
//Functions
$("#canvas").click(function (e) {
var yNames = ['upper', 'middle', 'lower'],
xNames = ['left', 'middle', 'right'];
alert(('The ' + yNames[Math.floor((e.offsetY * 3) / canvas.height)] + '-' + xNames[Math.floor((e.offsetX * 3) / canvas.width)] + ' box was clicked.')
.replace('middle-middle', 'middle'));
});
})