在jquery/canvas中预加载图像"Uncaught TypeError:类型错误"

Preload images in jquery/canvas "Uncaught TypeError: Type error"

本文关键字:quot Uncaught 错误 类型 TypeError 图像 jquery canvas 加载      更新时间:2023-09-26

我想在我的画布上预加载一个图像目录,以便在我需要它们的时候可以显示它们。

我在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将图像存储为什么?如果答案是"一个对象",那么为什么它不加载这个数组中的对象?

提前感谢您提供的任何建议

首先,需要将一个实际的图像元素传递给drawImage方法。现在你正在传递一个递延的。

接下来,Chrome和本地元素构造函数(new Image())有一个错误。

所以,简单地使用document.createElement("img"),它将做完全相同的事情-没有错误。

查看相关bug:

    关于帆布
  • :https://code.google.com/p/chromium/issues/detail?id=238071
  • 根本原因:https://code.google.com/p/chromium/issues/detail?id=245296

我在这里创建了一个简化的示例:http://jsfiddle.net/YVDpD/