JSFiddle - React, Tailwind, and code Playground
HTML
<div id="wrapper" style="background-color: red; width: 700px;">
<canvas id="canvas" width = "1664" height = "1000" style = "border:1px solid gray; width: 640px; height 400px; background-color: yellow; margin: 20px"> </canvas>
outside of canvas
</div>
JavaScript
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
var mycanvas = document.getElementById('canvas');
document.getElementById('wrapper').addEventListener('click', on_canvas_click, false);
function on_canvas_click(ev) {
var mousePos = getMousePos(mycanvas, ev);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(mycanvas, message);
}
function writeMessage(canvas, message) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '20pt Calibri';
context.fillStyle = 'black';
context.fillText(message, 10, 25);
}