[英]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.