[英]Get canvas pixel position from mouse coordinates
我有一個 16x16 的畫布,它使用 CSS ( width:90%; height: auto;
) 進行縮放,我正在嘗試將畫布上的鼠標坐標轉換為 16x16 像素之一。 我從onmousemove
事件中獲取它,雖然我可以獲得原始屏幕坐標,但我需要找到它在畫布上的位置。
嘗試這個:
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>
因此,您只需獲取坐標,獲取畫布的偏移量(全屏為0
),然后將其除以畫布的視覺寬度並乘以畫布的實際寬度。 如果你floor
,你會得到一個圓形的像素坐標。
上面的代碼適用於任何大小的畫布,因為它記住了它與屏幕的偏移量(也是鼠標坐標中的client
)。 所以無論畫布的寬度如何,這都應該返回正確的像素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.