【发布时间】:2021-08-30 18:28:17
【问题描述】:
对于我的像素艺术网站,我有一个相对于视口固定的画布,使用 css 进行缩放,并且具有 object-fit:contain;保持它的 div 的大小,无论在里面绘制或调整大小。 我需要获取鼠标点击坐标不缩放。由 e.y/e.x 收集的缩放坐标不会有用,因为 object-fit:contain;会改变纵横比。
这里有一些虚拟代码可以更好地解释我的问题:
var c = document.getElementById("scaledCanvas");
var ctx = c.getContext('2d');
c.height = 16; // varaible height
c.width = 16; // varaible width
for (var x = 0; x < c.width; x++) {
for (var y = 0; y < c.height; y++) {
ctx.fillStyle = "#" + Math.floor(Math.random() * 16777215).toString(16); // pick random color
ctx.fillRect(x, y, 1, 1); // draw pixel on canvas
}
}
c.addEventListener('click', function(e) {
//this is what i need help with, clickX and clickY need to give the pixel coordinates of the canvas, not the screen
let clickX = e.x - this.offsetLeft;
let clickY = e.y - this.offsetTop;
console.log(clickX + ", " + clickY);
}, false);
#scaledCanvas {
width: 50vw;
height: 50vh;
image-rendering: pixelated;
object-fit: contain;
background-color: black;
}
<!DOCTYPE html>
<html>
<body>
<canvas id="scaledCanvas" width="16" height="16">Canvas Not Supported</canvas>
</body>
</html>
【问题讨论】:
标签: javascript html onclick html5-canvas