EaselJS v1.0.0容器递归克隆时Bitmap无法克隆问题咨询
解决EaselJS v1.0.0克隆容器时Bitmap不被复制的问题
我之前在使用EaselJS的LoadQueue预加载图片后,也碰到过克隆容器时Bitmap“消失”的情况,咱们来一步步排查和解决这个问题:
首先排查基础操作是否正确
先确认你有没有做这几个关键步骤:
- 确保Bitmap已添加到父容器:你必须调用
cnt.addChild(bmp),不然克隆的时候自然找不到Bitmap。 - 用递归克隆参数:虽然Container的
clone()默认是递归克隆子元素,但显式传true更稳妥,比如const clonedCnt = cnt.clone(true)。 - 克隆后的容器要加到舞台:克隆完别忘了把新容器添加到舞台,比如
stage.addChild(clonedCnt),不然你根本看不到克隆后的元素。
验证克隆结果
如果上面的步骤都做了还是看不到Bitmap,可以通过控制台打印验证克隆后的容器内容:
const clonedCnt = cnt.clone(true); console.log("克隆后的子元素数量:", clonedCnt.numChildren); console.log("第一个子元素类型:", clonedCnt.getChildAt(0) instanceof createjs.Bitmap);
如果打印显示子元素数量为0,或者第一个子元素不是Bitmap,那说明克隆逻辑确实有问题。
修复Bitmap的克隆逻辑
EaselJS v1.0.0的Bitmap默认克隆方法理论上会复制image和相关属性,但有时候因为加载的图片对象(比如Blob URL或者跨域图片)的特殊情况,会导致克隆失败。这时候可以手动扩展Bitmap的克隆方法,确保所有属性都被正确复制:
// 在克隆操作前扩展Bitmap的clone方法 createjs.Bitmap.prototype.clone = function(recursive) { // 创建新的Bitmap实例,传入原始图片引用 const clone = new createjs.Bitmap(this.image); // 复制所有显示属性 clone.x = this.x; clone.y = this.y; clone.scaleX = this.scaleX; clone.scaleY = this.scaleY; clone.rotation = this.rotation; clone.alpha = this.alpha; clone.visible = this.visible; // 复制sourceRect(如果有的话) if (this.sourceRect) { clone.sourceRect = new createjs.Rectangle( this.sourceRect.x, this.sourceRect.y, this.sourceRect.width, this.sourceRect.height ); } return clone; };
完整可运行示例
这里给你一个完整的测试代码,你可以直接运行验证:
function test() { const { Bitmap, Container, LoadQueue, Shape, Stage, Ticker } = createjs; function loadImage() { const queue = new LoadQueue(); queue.addEventListener("fileload", addImage); // 替换成你的图片路径 queue.loadFile("image.jpg"); } function addImage(e) { const image = e.result; const bmp = new Bitmap(image); bmp.x = 50; bmp.y = 50; const cnt = new Container(); cnt.addChild(bmp); // 添加一个红色矩形作为对比,方便区分原始和克隆容器 const shape = new Shape(); shape.graphics.f("#ff0000").dr(0, 0, 100, 100); cnt.addChild(shape); // 扩展Bitmap克隆方法(如果需要的话) createjs.Bitmap.prototype.clone = function(recursive) { const clone = new createjs.Bitmap(this.image); clone.x = this.x; clone.y = this.y; clone.scaleX = this.scaleX; clone.scaleY = this.scaleY; clone.rotation = this.rotation; clone.alpha = this.alpha; clone.visible = this.visible; if (this.sourceRect) { clone.sourceRect = new createjs.Rectangle( this.sourceRect.x, this.sourceRect.y, this.sourceRect.width, this.sourceRect.height ); } return clone; }; // 递归克隆容器 const clonedCnt = cnt.clone(true); clonedCnt.x = 200; // 偏移克隆后的容器,避免重叠 // 初始化舞台并添加元素 const stage = new Stage("canvas"); stage.addChild(cnt, clonedCnt); // 启动渲染循环 Ticker.addEventListener("tick", () => stage.update()); } loadImage(); } // 调用测试函数 test();
额外注意点
- 如果你的图片是跨域的,需要在LoadQueue加载时配置跨域参数:
queue.loadFile({src: "image.jpg", crossOrigin: "anonymous"}),否则图片可能无法正常渲染,克隆后也看不到。 - 确保图片路径正确,加载失败的话原始Bitmap也会显示不出来,别把加载失败当成克隆问题。
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

