I am trying to adjust the size of the canvas according to the browser window, however when I do it I can no longer apply mousedown to the correct position of the image that is inside the canvas (it works when I click a position far below of the image but the idea is that it is in the correct position).
HTML:
<canvas id="cvs" width="1000px" height="500px"></canvas>
JS:
var canvas = document.getElementById('cvs');
var ctx = canvas.getContext('2d');
var PositionXImage = 0;
var PositionYImage = 100;
var image = new Image();
image.src = "../img/image.jpg";
image.onload = function () {
ctx.drawImage(image, PositionXImage, PositionYImage, 100, 100);
}
document.addEventListener('mousedown', function (e) {
var rect = canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
//image position
if (x >= PositionXImage && x <= (PositionXImage + 100) &&
y >= PositionYImage && y <= (PositionYImage + 100)) {
}
});
Note: To increase or reduce the size of the canvas depending on the size of the browser use max-width, I don't know if this was the best way.
question from:
https://stackoverflow.com/questions/65831367/fit-canvas-to-window-size-and-apply-mousedown-to-images-inside-canvas 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…