[英]get canvas mouse position on canvas
** Read before you mark as duplicate! ** 在标记为重复项之前先阅读! **
**
Getting the mouse position on the canvas nearly works fine. 使鼠标在画布上的位置几乎可以正常工作。
My window size is 800 x 600
我的视窗大小是
800 x 600
My canvas size is 400 x 300
: 我的画布大小是
400 x 300
:
canvas.width = 400;
canvas.height = 300;
My canvas css
size is 100% x 100%
: 我的画布
css
大小是100% x 100%
:
canvas {width: 100vw; height: 100vh;}
The problem is: if my mouse is in the middle of the canvas I get this mouse position: 400, 300
. 问题是:如果我的鼠标在画布中间,我会得到以下鼠标位置:
400, 300
。 If my window size was 1600 x 1200
I would get 800, 600
. 如果我的窗口大小是
1600 x 1200
我将得到800, 600
。
I would like to get the canvas position of the mouse. 我想获取鼠标的画布位置。 What I mean by this, is I'm looking to get
200, 150
, regardless of the window size. 我的意思是,无论窗口大小如何,我都希望得到
200, 150
。
How would I do this? 我该怎么做? Thank's for the help.
谢谢您的帮助。
You have to create conversion from model coordinates to screen coordinates and back. 您必须创建从模型坐标到屏幕坐标再返回的转换。 Here is good explanation for it: http://www.ckollars.org/canvas-two-coordinate-scales.html
这是一个很好的解释: http : //www.ckollars.org/canvas-two-coordinate-scales.html
You could paste this into your code. 您可以将此粘贴到您的代码中。
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;
}
then you could just reference the mouseX and mouseY somewhere else. 那么您可以在其他地方引用mouseX和mouseY。
//enter the rest of your code here.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.