即使使用image.onload
问题描述:
加载不正确的HTML5图像在第一次加载时,我正在使用EaselJS和第一次加载后,我清除我的缓存,我的图像加载在左上角默认大小(基本上是x :0,y:0,scale:1)而不是我指定的。我得到这是一个异步图像加载错误,但我用image.onload调用完成所有实际绘图的函数,并且这似乎不会影响任何东西。即使使用image.onload
这里是相关的代码。我也提供了一个显示缓存问题的小提琴,但由于跨域图像,应用程序的实际功能无法正常工作。 https://jsfiddle.net/a9m66tcL/2/
function initToolbar(stage){
let toolbarImages = [];
let toolbar = new createjs.Shape();
toolbar.graphics.beginFill("black");
toolbar.graphics.drawRect(0, 580, 960, 120);
toolbarContainer.addChild(toolbar);
// load the source images:
for (name of imageManifest){
let image = new Image();
image.src = "SacredSpace/"+ name +".png";
image.onload = loadToolbarImage(toolbarImages, image);
}
stage.addChild(toolbarContainer);
}
function loadToolbarImage(toolbarImages, image) {
toolbarImages.push(image);
let bitmap = new createjs.Bitmap(image);
toolbarContainer.addChild(bitmap);
bitmap.x = toolbarImages.length * 150 + 100;
bitmap.y = 640;
bitmap.regX = bitmap.image.width/2 | 0;
bitmap.regY = bitmap.image.height/2 | 0;
if (image.width > image.height){
bitmap.scaleX = bitmap.scaleY = 100/ image.width
}else{
bitmap.scaleX = bitmap.scaleY = 100/ image.height
}
bitmap.on("mousedown", function (evt) {
addObject(image)
update = true;
});
}
答
这是不正确的:
image.onload = loadToolbarImage(toolbarImages, image);
而是射击onload
的,它被立即调用,并将结果返回onload处理。正确的语法是:
image.onload = loadToolbarImage; // Pass the function by reference
因为它看起来像你正在使用ES6,使用方法:
image.onload = e => loadToolbarImage(toolbarImages, e);
要沿着ES5传递参数,你可以做这样的事情:
image.onload = loadToolbarImage.bind(this, toolbarImages, image);
我会进一步建议将toolbarImages
移动到您的init函数之外,以便它可以访问,并使用图像的事件目标。这样你就不会手动传播图像和数组。
干杯,
真棒谢谢你我抓挠了我的脑袋,但这使得很多道理。我将onload设置为函数调用的返回值,但我应该将其设置为函数本身。 我用这个,它似乎已经解决了我的问题。 'image.onload =()=> loadToolbarImage(toolbarImages,image);' – FFF