gpt4 book ai didi

javascript - Easeljs 形状未定义

转载 作者:行者123 更新时间:2023-12-03 01:54:59 26 4
gpt4 key购买 nike

我需要使用 Shape 对象创建可拖动的随机矩形。此函数在单击鼠标的位置创建新的矩形。

var rects = [];
var i=0;
var stage;
window.onload = function() {
canvas = document.getElementById("drawingCanvas");
context = canvas.getContext("2d");
stage = new createjs.Stage("drawingCanvas");

canvas.onclick = canvasClick;
}

function canvasClick(e) {
var d=Math.random()*150;
rects[i] = new createjs.Shape();
rects[i].graphics.beginStroke("black").
beginFill("RGB"+"(" + parseInt(Math.random()*255) +"," +
parseInt(Math.random()*255)+"," +parseInt(Math.random()*255)+")").
drawRect(e.offsetX-d/2,e.offsetY-d/2,d,d);
stage.addChild(rects[i]);
rects[i].on("mousedown", function (evant) {
console.log("jdfh");
var offset = {
x: evant.target.x - evant.stageX,
y: evant.target.y - evant.stageY
};
rects[i].on("pressmove", function (evant) {
evant.target.x = evant.stageX + offset.x;
evant.target.y = evant.stageY + offset.y;
stage.update();
});
});
i++;
stage.update();
}

但是当我尝试拖动矩形时,它显示: rect.js:47 Uncaught TypeError: Cannot read property 'on' of undefined

at a.<anonymous> (file:///C:/Users/Vasya/Downloads/redactor%20(1)/rect/public_html/rect.js:47:39)
at easeljs-0.8.2.min.js:12
at a.b._dispatchEvent (easeljs-0.8.2.min.js:12)
at a.b.dispatchEvent (easeljs-0.8.2.min.js:12)
at a.b._dispatchMouseEvent (easeljs-0.8.2.min.js:13)
at a.b._handlePointerDown (easeljs-0.8.2.min.js:13)
at a.b._handleMouseDown (easeljs-0.8.2.min.js:13)
at HTMLCanvasElement.f (easeljs-0.8.2.min.js:13)

最佳答案

在您的最新更新中,mousedown 处理程序中的 i 变量始终比您创建的最后一项大 1,因为稍后会在 i 变量之后引用它已增加。

相反,您也可以使用 evant.target 来实现此目的。

rects[i].on("mousedown", function (evant) {
console.log("jdfh");
var offset = {
x: evant.target.x - evant.stageX,
y: evant.target.y - evant.stageY
};

// Note: store the listener handler to remove it later
var listener = evant.target.on("pressmove", function (evant) {
evant.target.x = evant.stageX + offset.x;
evant.target.y = evant.stageY + offset.y;
stage.update();
});

// Remove the pressmove handler
evant.target.on("pressup", function(evant) {
evant.target.off("pressmove", listener);
evant.remove(); // Remove this pressup handler too
});
});

提醒删除 pressmove 处理程序,因为每次您按下对象时它都会再次添加。这是因为您的处理程序只是一个匿名函数,因此每次都会创建一个新函数。您不必每次都添加“pressmove”事件,您只需添加一次即可,但您必须使偏移量全局化,或将其存储在对象上。

希望有帮助。

关于javascript - Easeljs 形状未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50281559/

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