如何解决“ TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage'”?

时间:2018-12-17 08:54:42

标签: javascript

我是一名JavaScript初学者,正在关注一本名为“使用<代码>创建”的书,但我在使用代码时遇到了麻烦。我一直在跟着这本书,但是当我尝试运行它时,出现此错误:

  

未捕获的TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型

我一直在将代码输入到纯文本编辑器中,并在Chrome上进行查看。如何解决此错误?

如果运行该代码段,您应该能够看到错误。

//CONSTANTS
var CANVAS_WIDTH = 800;
var CANVAS_HEIGHT = 600;

var GROUND_Y = 540;

//SETUP
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
document.body.appendChild(canvas);

var cameraX = 0;
var bushData = generateBushes();

var bush1Image = new Image();
bush1Image.src = 'bush1.png';

var bush2Image = new Image();
bush2Image.src = 'bush2.png';

window.addEventListener('load', start);

function start() {
    window.requestAnimationFrame(mainLoop);
}

function generateBushes() {
    var generatedBushData = [];
    var bushX = 0;
    while (bushX < (2 * CANVAS_WIDTH)) {
        var bushImage;
        if (Math.random() >= 0.5) {
            bushImage = bush1Image;
        } else {
            bushImage = bush2Image
        }
        generatedBushData.push({
            x: bushX,
            y: 80 + Math.random() * 20,
            image: bushImage
        });
        bushX += 150 + Math.random() * 200;
    }
    return generatedBushData;
}

//MAIN LOOP
function mainLoop() {
    update();
    draw();
    window.requestAnimationFrame(mainLoop);

}

//UPDATING
function update() {

    //Update bushes.
    for (var i = 0; i < bushData.length; i++) {
        if ((bushData[i].x - cameraX) < -CANVAS_WIDTH) {
            bushData[i].x += (2 * CANVAS_WIDTH) + 150;
        }
    }
}

//DRAWING
function draw() {

    //Draw the bushes
    for (var i = 0; i < bushData.length; i++) {
        c.drawImage(
            bushData[i].image,
            bushData[i].x,
            GROUND_Y - bushData[i].y);
    }

}

1 个答案:

答案 0 :(得分:1)

DanieleAlessandra用手指指着a comment中的错误:image中的对象中的bushDataundefined,因为您正在调用{{1 }} 太快了。你有:

generateBushes

但是您需要在调用var bushData = generateBushes(); var bush1Image = new Image(); bush1Image.src = 'bush1.png'; var bush2Image = new Image(); bush2Image.src = 'bush2.png'; 之前初始化bush1Imagebush2Image。只需将generateBushes移至var bushData = generateBushes();之后即可解决。