Draw part of an image inside html5 canvas

canvas, html, html5-canvas, javascript, jquery

Solution

Ok, first of all thanks so much for the fiddle - makes everything a billion times easier.

There are two three errors in your code - the first is the tankImg.onload function. The onload function only fires once - when the image first loads.

What you want is tankImg.complete which will return true if loaded and false if not.

Secondly, you cannot assign 'ch - this.h' for the y property because 'this' isn't defined until, well, you finish defining it. What you can do is set the y value in your draw code.

Thirdly in javascript you can't do var cw, ch = 400;

 $(document).ready(function () {
     var cw = 400;
     var ch = 400;
     var ctx = $("#MyCanvas")[0].getContext("2d");
     var tankImg = new Image();
     tankImg.src = "http://oi62.tinypic.com/148yf7.jpg";
     var Fps = 60;
     var PlayerTank = {
         x: cw / 2,
         w: 84,
         h: 84,
         Pos: 2,
         draw: function () {
             ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, ch - this.h, this.w, this.h);
         }
     };

     var game = setInterval(function () {
         if (tankImg.complete) {
             PlayerTank.draw();
             PlayerTank.x++;
         }
     }, 1000 / Fps);
 });

Here is the completed jsfiddle with bonus movement for fun.

Edit: Ken's version of handling the .onload is much better.

Problem

I am trying to draw the first Green tank inside my canvas but i think i am missing something in my code jsfiddle: ``` draw: function () { tankImg.onload = function () { ctx.drawImage(tankImg, this.Pos * this.w, 0, this.w, this.h, this.x, this.y, this.w, this.h); }; } ``` Can anyone help me please?

Original source