gpt4 book ai didi

JavaScript- 将鼠标 X 和 Y 位置存储在变量中,并随着鼠标移动不断更新它们

转载 作者:行者123 更新时间:2023-11-30 06:34:53 24 4
gpt4 key购买 nike

我有一个显示大量图像的 HTML5 Canvas 。其中一些图像是可拖动的,而另一些则不是。我使用 KineticJS 库的本地副本添加了可拖动功能(我使用本地副本是因为我想稍微编辑一两个函数)。

我现在要做的是创建几个 JS 变量来存储光标在 Canvas 上的当前位置。我希望能够这样做的原因是,当用户拖动其中一个可拖动图像时,我可以检测光标的位置,并检查他们是否已将其拖动到正确的位置。

我编写了以下函数来执行此操作:

function getMousePosition(mouseX, mouseY){
mouseX = e.clientX;
mouseY = e.clientY;
console.log("mouseX = " + mouseX);
console.log("mouseY = " + mouseY);
}

我从 KineticJS _mousemove 函数中调用这个函数,所以这个函数现在看起来像这样:

_mousemove: function(evt) {
this._setUserPosition(evt);
var dd = Kinetic.DD;
var obj = this.getIntersection(this.getUserPosition());
getMousePostion(mouseX, mouseY);

if(obj) {
var shape = obj.shape;
if(shape) {
if((!dd || !dd.moving) && obj.pixel[3] === 255 && (!this.targetShape || this.targetShape._id !== shape._id)) {
if(this.targetShape) {
this.targetShape._handleEvent('mouseout', evt, shape);
this.targetShape._handleEvent('mouseleave', evt, shape);
}
shape._handleEvent('mouseover', evt, this.targetShape);
shape._handleEvent('mouseenter', evt, this.targetShape);
this.targetShape = shape;
}
else {
shape._handleEvent('mousemove', evt);
}
}
}
/*
* if no shape was detected, clear target shape and try
* to run mouseout from previous target shape
*/
else if(this.targetShape && (!dd || !dd.moving)) {
this.targetShape._handleEvent('mouseout', evt);
this.targetShape._handleEvent('mouseleave', evt);
this.targetShape = null;
}

// start drag and drop
if(dd) {
dd._startDrag(evt);
}
}

我遇到的问题是,当我在浏览器中查看我的页面并将光标移到 Canvas 上时,每次移动光标时都会出现 Firebug 控制台错误:“getMousePostion 未定义”。其中一些错误仅说明这一点,其中一些错误旁边有一个小的“+”。

如果我展开其中一个旁边有“+”的错误,我会得到以下附加信息:

_mousemove()kinetic.js (line 3443)
evt = mousemove clientX=15, clientY=229
(?)()kinetic.js (line 3417)
evt = mousemove clientX=15, clientY=229

每个可扩展的错误都为 clientXclientY 显示不同的数字,这表明我的函数显然是在光标四处移动时获取光标的 x 和 y 坐标 Canvas 。所以我想知道的是,为什么我会收到错误消息,告诉我 getMousePosition 未定义?

最佳答案

您正在尝试获取不存在的对象的属性,即 e。您应该传递事件对象,而不是将 mouseXmouseY 传递给函数。

//you're passing parameters that don't exist in _mousemove
function getMousePosition(mouseX, mouseY){
mouseX = e.clientX; //and trying to use e, which doesn't exist
mouseY = e.clientY;
//also passed parameters aren't meant to be used as local variables like this
console.log("mouseX = " + mouseX);
console.log("mouseY = " + mouseY);
}

将您传递的参数更改为事件对象,并创建 mouseXmouseY 作为局部变量,它应该可以工作。另一个非常大的问题是,在 _mousemove 中,您正在调用函数 getMousePostion。注意拼写。你忘记了一个“我”。

function getMousePosition(e){
var mouseX = e.clientX;
var mouseY = e.clientY;
console.log("mouseX = " + mouseX);
console.log("mouseY = " + mouseY);
}

_mousemove: function(evt) {
...
getMousePosition(evt);
...

关于JavaScript- 将鼠标 X 和 Y 位置存储在变量中,并随着鼠标移动不断更新它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15248238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com