-1

我正在尝试在 Adob​​e Animate 2015 中像http://www.flashuser.net/eyes-following-mouse-cursor-as3这样的光标来关注

function getMousePos(canvasDom, mouseEvent) {
  var rect = canvasDom.getBoundingClientRect();
  return {
    x: mouseEvent.clientX - rect.left,
    y: mouseEvent.clientY - rect.top
  };
}

canvas.addEventListener("mousemove", function (e) {
    mousePos = getMousePos(this, e);

    var xx = mousePos.x - this.Reye.x;
    var yy = mousePos.y - this.Reye.y;
    var radiusR1 = Math.atan2(yy, xx);
    var degreeR1 = radiusR1 / (Math.PI / 180);
    this.Reye.rotation = degreeR1;

}, false);

但我在浏览器中有错误

TypeError: Cannot read property 'x' of undefined

这段代码工作正常

this.addEventListener("click", fl_MouseClickHandler.bind(this));
function fl_MouseClickHandler(evt)
{
    var xx = stage.mouseX - this.Reye.x;
    var yy = stage.mouseY - this.Reye.y;
    var radiusR1 = Math.atan2(yy, xx);
    var degreeR1 = radiusR1 / (Math.PI / 180);
    this.Reye.rotation = degreeR1;
}
4

1 回答 1

1

你的范围是错误的。

您添加一个匿名函数作为内联的侦听器:

canvas.addEventListener("mousemove", function (e) {

顺便说一句,这是不好的做法,因为您很难再次删除侦听器。延迟侦听器将阻止对象被收集并可能导致内存泄漏。

无论如何,匿名函数(闭包)的作用域是全局对象。this不会指向定义函数的范围。

在第二个示例中,您绑定了范围:

fl_MouseClickHandler.bind(this)

对于命名函数,这不是必需的。

附带说明:使用类型并为事件类型使用定义的常量,例如MouseEvent.CLICKfor "click"- 防止拼写错误并允许代码完成。

于 2016-08-31T22:05:15.183 回答