Draw part of the image inside the html5 canvas

I'm trying to draw the first green tank inside my canvas, but I think I missed 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 anybody help me?

+4
source share
2 answers

Well, first of all, thanks for the violin - everything is billions of times lighter.

There are two three errors in the code: the first is the tankImg.onload function. The onload function works only once - when the image is first loaded.

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

-, 'ch - this.h' y, 'this' , . , , - y .

-, javascript 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);
 });

jsfiddle .

: Ken .onload .

+4

, :

undefined ( NaN drawImage()):

var cw; /// is not defined

, .

onload . onload, , , , onload .

:

var tankImg = new Image();
tankImg.onload = start;      /// add the onload handler before setting src.
tankImg.src = "http://oi62.tinypic.com/148yf7.jpg";

setInterval start:

var game;   /// keep this var outside (in global)

function start() {
    game = setInterval(function () {
        PlayerTank.draw();
    }, 1000 / Fps);
}

, this.h , . ( ) , draw(), .

:

+1

Source: https://habr.com/ru/post/1525764/


All Articles