简体   繁体   中英

Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state

I'm using canvas to create a 2d game using Javascript and HTML. I 'm trying to insert a background image in my canvas using Javascript but Chrome shows me the same error (Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state). In some solutions I read to insert the image.onload function to load the image: If I do this there are no errors in the console but the image doesn't appears, neither a simple console.log to test the function. Here is my code. Thank you for the help.

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d')

canvas.width= 1024
canvas.height = 576

//The class that I did for the image

class Sprite {

    constructor({position}) {
        this.position = position
        this.image = new Image()
        this.image.src = 'B2.png'
    }  

    draw(){
            c.drawImage(this.image,this.position.x, this.position.y)
        }
}

const background = new Sprite({
    position:{
        x :0,
        y :0,
    }
})


The function where I recall the draw function

function animate () {
    //richiama ogni volta la funzione
    window.requestAnimationFrame(animate)
    c.fillStyle= 'white'
    c.fillRect(0, 0, canvas.width, canvas.height)
    background.draw()
    //se tengo premuto continua ad andarea destra,altrimenti si stoppa 
    //perchè la velocità viene risettata a 0
    player.velocity.x = 0
    if(keys.d.pressed) {
        player.velocity.x = 1
    }else if (keys.a.pressed) {
        player.velocity.x = -1
    }
    player.update()
    player2.update()
    
}



I expect to fix the png image in the rectangular canvas.

Solved: I was trying doing this with Parcel server in many ways and it didn't work. I switched to the Visual Studio Code and then it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM