JSFiddle - React, Tailwind, and code Playground
by joseph4tw
HTML
<canvas id="myCanvas" height="400" width="400"></canvas>
CSS
canvas {
background-color: #d0d0d0;
}
JavaScript
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const canvasX = canvas.offsetLeft;
const canvasY = canvas.offsetTop;
context.fillStyle = 'green';
context.fillRect(10, 10, 100, 100);
canvas.addEventListener('click', function(event) {
const mouseX = event.clientX - canvasX;
const mouseY = event.clientY - canvasY;
if ((10 <= mouseX && mouseX <= 100) && (10 <= mouseY && mouseY <= 100)) {
console.log('clicked inside square');
} else {
console.log('clicked outside of square');
}
});