javascript - How to fix "TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D&

I am a beginner JavaScript programmer and I am following a book called "Create with < code >

I am a beginner JavaScript programmer and I am following a book called "Create with < code >" and I am having trouble with the code. I have been following along with the book but when I have tried running it, I get this error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)

I have been typing the code into a plain-text editor and viewing it on Chrome. How do I fix this error?

If you run the snippet you should be able to see the error.

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

}

I am a beginner JavaScript programmer and I am following a book called "Create with < code >" and I am having trouble with the code. I have been following along with the book but when I have tried running it, I get this error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)

I have been typing the code into a plain-text editor and viewing it on Chrome. How do I fix this error?

If you run the snippet you should be able to see the error.

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

}

Share Improve this question edited Dec 17, 2018 at 9:56 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked Dec 17, 2018 at 8:54 J2t0n4J2t0n4 312 silver badges8 bronze badges 12
  • The error is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)' and it is on line 163. – J2t0n4 Commented Dec 17, 2018 at 8:58
  • If I search on that error, I get a lot of hits. Have you read through those various pages to see if they answer your problem? – T.J. Crowder Commented Dec 17, 2018 at 9:01
  • Yes, I have looked through a couple of the pages but none seemed to help. I have stripped the code back so it is easier to understand and still has the same error. Does this make it any easier? – J2t0n4 Commented Dec 17, 2018 at 9:11
  • The error is on this line: c.drawImage(bushData[i].image, bushData[i].x, GROUND_Y - bushData[i].y); The bushData variable contains an array of objects like that: {x: number, y: number, image: undefined} since image is undefined it cannot be drawn on canvas. you are missing the part in which those properties shoul be initialized. – DanieleAlessandra Commented Dec 17, 2018 at 9:12
  • @DanieleAlessandra ,but I have the images on in the same folder as the html document and i have defined the image in this part: generatedBushData.push({ x: bushX, y: 80 + Math.random() * 20, image: bushImage right? – J2t0n4 Commented Dec 17, 2018 at 9:19
 |  Show 7 more ments

1 Answer 1

Reset to default 3

DanieleAlessandra put his finger on the error in a ment: image in the objects in bushData is undefined, because you're calling generateBushes too soon. You have:

var bushData = generateBushes();

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

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

but you need to initialize bush1Image and bush2Image before calling generateBushes. Just moving var bushData = generateBushes(); to after bush2Image.src = 'bush2.png'; fixes it.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745269494a4619657.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信