我正在开发一个项目,该项目要求用户将图像加载到 Canvas 中,该 Canvas 根据他们所做的选择放置在灯箱中。
在用户单击按钮之前不会加载任何图像,然后在 XHR 请求中接收图像 URL。
我在加载图像和推迟执行后续代码时遇到问题...
我的图像加载功能如下所示..
function preloadImage(url){
var img = new Image();
if (!img.complete) {
console.log('not complete');
//return false;
}
if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
console.log('no width');
//return false;
}
img.onerror='Image failed to load...';
img.src = url;
}
在代码中,我在设置 Canvas 元素之前调用它...这...
preloadImage(url);
setstage(url);
Canvas 有时会及时获取图像来设置我的舞台,但有时则不然,所以我有一个空白的舞台:/。有没有办法可以做到这一点并以某种方式解决此图像预加载问题?
最佳答案
尝试在 preloadImage 中使用回调:
function preloadImage(url, callback) {
var img = new Image();
img.onerror = function() {
callback('error', url, img);
};
img.onload = function() {
callback(null, url, img);
};
img.src = url;
}
preloadImage(url, function(err, url, img) {
if (err) {
console.log('something wrong!!', url);
return;
}
//get more params from img..
setstage(url);
});
..
function foo() {
//here are some params
var srcx = 1, id = 2, x = 3, y = 4;
preloadImage(url, function(err, url, img) {
if (err) {
console.log('something wrong!!', url);
return;
}
//more params
var width = 5, height = 6;
setstage(srcx, id, x, y, width, height);
});
}
关于窗口加载后Javascript预加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21106667/