我的目标是从鼠标的x和y位置获取实时更新输入。 y位置效果很好,但是当我加入x位置时,除了'NaN'之外我什么都得不到。
为什么这也不适合X职位?这不是如何通过函数传递对象?多个对象是问题吗?
这是我的代码:
canvas.addEventListener('mousemove',
function(evt){
var mousePos = calculateMousePosY(evt);
paddle1Y = mousePos.y;
//HERE IS WHERE I WANT X POSITION AS WELL
paddle1X = mousePos.x; //Why doesn't this work?
});
function calculateMousePos(evt){
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollleft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return{
x:mouseX,
y:mouseY
}
答案 0 :(得分:1)
将var mouseX = ... - root.scrollleft;
更改为var mouseX = ... - root.scrollLeft;
将' l'在' left'。
此外,您的功能称为calculateMousePos
而不是calculateMousePosY
。删除" Y"。
答案 1 :(得分:0)
您的代码有两处变化,
var mousePos = calculateMousePosY(evt);
和function calculateMousePos(evt){...}
有一个额外的" Y"。scrollLeft
,有一个大写" L"。请找到以下代码:[希望有帮助]
<强> HTML:强>
<canvas id="myCanvas" width="578" height="200"></canvas>
<强>使用Javascript:强>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
canvas.addEventListener('mousemove',function(evt){
var mousePos = calculateMousePos(evt);
var values = 'Mouse position:' + mousePos.x + ',' + mousePos.y;
display(canvas, values);
});
function calculateMousePos(evt){
var rect = canvas.getBoundingClientRect();
var root = document.documentElement;
var mouseX = evt.clientX - rect.left - root.scrollLeft;
var mouseY = evt.clientY - rect.top - root.scrollTop;
return{
x:mouseX,
y:mouseY
}
}
function display(canvas, values) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.font = '18pt Calibri';
context.fillStyle = 'black';
context.fillText(values, 10, 25);
}
&#13;
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;