简体   繁体   English

从鼠标坐标获取画布像素位置

[英]Get canvas pixel position from mouse coordinates

I have a 16x16 canvas that is scaled with CSS ( width:90%; height: auto; ) and I'm attempting to convert mouse coordinates on the canvas to one of the 16x16 pixels.我有一个 16x16 的画布,它使用 CSS ( width:90%; height: auto; ) 进行缩放,我正在尝试将画布上的鼠标坐标转换为 16x16 像素之一。 I'm taking it from an onmousemove event, and while I can get the raw screen coordinates, I need to get where it lies on the canvas.我从onmousemove事件中获取它,虽然我可以获得原始屏幕坐标,但我需要找到它在画布上的位置。

Try this:尝试这个:

 const canvas = document.querySelector( 'canvas' ); canvas.addEventListener( 'mousemove', event => { const bb = canvas.getBoundingClientRect(); const x = Math.floor( (event.clientX - bb.left) / bb.width * canvas.width ); const y = Math.floor( (event.clientY - bb.top) / bb.height * canvas.height ); console.log({ x, y }); });
 html,body { height: 100%; } canvas { width: 100%; height: 100%; }
 <canvas width="16" height="16"></canvas>

So you simply take the coordinate, take of the offset of the canvas (fullscreen that would be 0 ), then divide it by the visual width of the canvas and multiply by the actual width of the canvas.因此,您只需获取坐标,获取画布的偏移量(全屏为0 ),然后将其除以画布的视觉宽度并乘以画布的实际宽度。 If you floor that you get a rounded pixel coordinate.如果你floor ,你会得到一个圆形的像素坐标。

The above code works for any size canvas, since it keeps in mind the offset it has from the screen (also client in mouse coordinate).上面的代码适用于任何大小的画布,因为它记住了它与屏幕的偏移量(也是鼠标坐标中的client )。 SO whatever the width of your canvas, this should return the correct pixel.所以无论画布的宽度如何,这都应该返回正确的像素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM