Javascript 我不能用加载的图像在画布上绘制

Javascript 我不能用加载的图像在画布上绘制,javascript,html,image,canvas,html5-canvas,Javascript,Html,Image,Canvas,Html5 Canvas,我不能在画布上画图像。我确信图像是在绘制之前加载的。 如果我确定图像已加载,为什么我不能绘制精灵 错误如下所示 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)' 和

我不能在画布上画图像。我确信图像是在绘制之前加载的。 如果我确定图像已加载,为什么我不能绘制精灵

错误如下所示

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'
和一个示例代码:

//Canvas
var canvas;
var ctx;
var sprite;

var load = function(){

    canvas = document.createElement("canvas");
    ctx = canvas.getContext("2d");

    canvas.width = 400;
    canvas.height = 300;
    document.body.appendChild(canvas);

    var spriteSheet = new Image();
    spriteSheet.onload = function(){
        initSprites(this);
        draw();
    };
    spriteSheet.src = "http://users.aber.ac.uk/jov2/sprite.png";
};

var draw = function(){
    ctx.drawImage(sprite,0,0);
}

var initSprites = function(img){
    sprite = new Sprite(img, 0,  0, 32, 32);
};

function Sprite(img, x, y, width, height) {
    this.img = img;
    this.x = x*2;
    this.y = y*2;
    this.width = width*2;
    this.height = height*2;
};

因为您试图绘制的是精灵实例,而不是图像。试试这个

var draw = function(){
    ctx.drawImage(sprite.img,0,0);
}