Draw part of an image inside HTML5 canvas


If you want to draw part of an image inside canvas, the image onload function only fires once when the image first loads into the browser. 

Let us see the example:

$(document).ready(function () {
   var cw1 = 200;
   var ch1 = 300;
   var ctx1 = $("#myCanvas")[0].getContext("3d");
   var myImg1 = new Image();
   myImg1.src = "http://oi62.tinypic.com/148yf7.jpg";
   var Fpst = 60;

   var Player1Tank = {
      x: cw1 / 2,
      w: 85,
      h: 85,
      Pos: 3,
      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);
});

Updated on: 30-Jan-2020

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements