[英]get canvas mouse position on canvas
** 在標記為重復項之前先閱讀! **
使鼠標在畫布上的位置幾乎可以正常工作。
我的視窗大小是800 x 600
我的畫布大小是400 x 300
:
canvas.width = 400;
canvas.height = 300;
我的畫布css
大小是100% x 100%
:
canvas {width: 100vw; height: 100vh;}
問題是:如果我的鼠標在畫布中間,我會得到以下鼠標位置: 400, 300
。 如果我的窗口大小是1600 x 1200
我將得到800, 600
。
我想獲取鼠標的畫布位置。 我的意思是,無論窗口大小如何,我都希望得到200, 150
。
我該怎么做? 謝謝您的幫助。
您必須創建從模型坐標到屏幕坐標再返回的轉換。 這是一個很好的解釋: http : //www.ckollars.org/canvas-two-coordinate-scales.html
您可以將此粘貼到您的代碼中。
document.getElementById("canvasId").addEventListener('mousemove',function(event){mousePos(event);});
function getMousePos(e){
var rect = canvas.getBoundingClientRect();
//this gets your canvas size.
return {
x: Math.round(e.clientX - rect.left),
y: Math.round(e.clientY - rect.top)
};
function mousePos(e){
var pos = getMousePos(e);
var mouseX = pos.x;
var mouseY = pos.y;
}
那么您可以在其他地方引用mouseX和mouseY。
//enter the rest of your code here.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.