user1776524
user1776524

Reputation: 127

drawing image on html5 canvas

I'm pretty new to js and have only done a little bit of html however this seems like something that would be simple: I'm just trying to draw an image onto a canvas! If adding the new image to my main div (gameObjectElement) it works fine, but when trying to draw it on a canvas it doesn't show. The fill text shows up on the canvas so I believe the context stuff is correct.

        var marthPic = new Image();
        marthPic.src ='images/marth.jpg';

        $(gameObjectElement).append(marthPic);

        var c=document.getElementById("myCanvas");
        var ctx=c.getContext("2d");
        ctx.font="30px Arial";
        ctx.fillText("Hello World",300,50);
        ctx.drawImage(marthPic, 100, 100);

Any ideas?

thanks

Upvotes: 1

Views: 171

Answers (2)

Casey Chu
Casey Chu

Reputation: 25463

You need to wait for the image to actually be loaded before you add it to the canvas. You can do this with an onload handler:

var marthPic = new Image();
marthPic.src ='images/marth.jpg';
$(gameObjectElement).append(marthPic);

marthPic.onload = function () {
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.font="30px Arial";
    ctx.fillText("Hello World",300,50);
    ctx.drawImage(marthPic, 100, 100);  
};

Upvotes: 4

Nogusta
Nogusta

Reputation: 919

Edited because I'm a noob (lucky cache hit):

    <script>
     var c=document.getElementById("myCanvas");
     var ctx=c.getContext("2d");

     var marthPic = new Image();
     marthPic.src = 'images/marth.jpg';
     marthPic.onload = function() {
        ctx.drawImage(marthPic,10,10);
     };

 </script> 

Upvotes: 1

Related Questions