【发布时间】:2013-06-06 00:02:32
【问题描述】:
我想将图像目录预加载到我的画布中,以便在我需要时可以显示它们。
I found this question on stackoverflow 并且接受的答案非常有帮助。 它们的函数遍历图像位置数组,然后(我假设)将它们预加载到画布上。
使用此功能预加载它们后,我很难实际显示它们。我很清楚单张图片的加载方式-
img = new Image();
img.src = imgLocation;
img.onload = function() {
context.drawImage(img, 0, 0);
}
但由于它们已经加载,我假设我不需要使用img.onload 或除context.drawImage 之外的任何上述代码来实际显示图像。
当我尝试从(我只能假设是包含所有图像的输出数组)加载图像时,我得到一个类型错误。当我在任何索引处检查数组中的内容(带有console.log())时,它会显示[object, Object]
我的代码代码如下所示:
var framesArr = new Array();
var framesAmnt = 300; // we would normally get this number from the PHP side of things
function ldBtn(){
//load all frames locations into framesArr
var i=0;
for (i=0;i<=(framesAmnt-1);i++){
framesArr[i] = "frames/Frame" + i + ".png";
}
//preload them
preloadImages(framesArr, preloadDone);
}
var deferreds = [];
var deferred;
function preloadImages (paths, callback) {
$.each(paths, function (i, src) {
deferred = $.Deferred(),
img = new Image();
deferreds.push(deferred);
img.onload = deferred.resolve;
img.src = src;
});
$.when.apply($, deferreds).then(callback);
}
function preloadDone(){
//any old index number will do. *Shruggs*
context.drawImage(deferreds[2], 0, 0); //this will cause a type error.
}
如何在画布上显示由preloadImages 函数加载的图像?
我想我不完全明白当img = new Image(); img.src = imgLocation; img.onload = function() 发生时会发生什么。 javascript/jquery 将图像存储为什么?如果答案是“一个对象”,那它为什么不加载这个数组中的对象呢?
提前感谢您提供的任何建议。
【问题讨论】:
标签: javascript jquery html html5-canvas preloading