我无法在加载图像的画布上绘制

I can not draw on canvas with loaded image

本文关键字:绘制 图像 加载      更新时间:2023-09-26

我无法在画布上绘制图像。我确信在绘制之前已经加载了图像。如果我确信图像已加载,为什么我不能绘制精灵?

错误如下

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;
};

代码

因为您要绘制的是Sprite而不是Image的实例。试试这个

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