admin管理员组

文章数量:1279244

I'm following the tutorials and setting up my code.. but when I run it I can an error message

"(index):18 Uncaught InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state."

This is my code which Im running in the indexSoccer.html file,

    var ctx = document.getElementById("ctx").getContext("2d");

    var Img = {};
    Img.player = new Image();
    Img.player.src = 'images/cat1sprite.png';

    drawPlayer = function(player){
        ctx.save();
        var x = player.x;
        var y = player.y;
        ctx.drawImage(Img.player, x, y);
        ctx.restore();

    }

and my directory looks like the following -

any ideas why?

I'm following the tutorials and setting up my code.. but when I run it I can an error message

"(index):18 Uncaught InvalidStateError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state."

This is my code which Im running in the indexSoccer.html file,

    var ctx = document.getElementById("ctx").getContext("2d");

    var Img = {};
    Img.player = new Image();
    Img.player.src = 'images/cat1sprite.png';

    drawPlayer = function(player){
        ctx.save();
        var x = player.x;
        var y = player.y;
        ctx.drawImage(Img.player, x, y);
        ctx.restore();

    }

and my directory looks like the following -

any ideas why?

Share Improve this question asked Apr 10, 2016 at 13:13 joejoe 1,7234 gold badges18 silver badges37 bronze badges 3
  • 1 “The HTMLImageElement provided is in the 'broken' state” – w3/TR/html5/embedded-content-0.html#img-error – C3roe Commented Apr 10, 2016 at 13:26
  • tried a different file, same error. – joe Commented Apr 10, 2016 at 15:36
  • But <img src="images/cat1sprite.png"> put into the HTML code would show the image …? – C3roe Commented Apr 10, 2016 at 15:42
Add a ment  | 

2 Answers 2

Reset to default 6

Because you try to draw the image before it is loaded.

var Img = {};
Img.player = new Image();
Img.player.onload = function() {
  // Try to draw your image only after this function has been called.
  // eg: drawPlayer(Player1);
}
Img.player.src = 'images/cat1sprite.png';

Also, make sure to look into the console for errors (in case the image path is wrong).

I think that the problem is ctx.save(); ctx.restore(); you don't need them, try without them like in this tutorial. Also check the path of the image and that the image is correct (maybe you have a png called .jpg or something like this)

本文标签: javascriptWhy isn39t my image being drawn on HTML5 canvasStack Overflow