Drawing an image inside canvas - Javascript Canvas

Javascript examples for Canvas:image

Description

Drawing an image inside canvas

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/* ww  w .j av a  2s  . c  o m*/
   $(document).ready(function () {
       var ch = 400;
       var cw = 400;
       var fps = 60;
       var canvas = $('#My_Canvas')[0];
       canvas.width = 400;
       canvas.height = 400;
       var ctx = canvas.getContext("2d");
       var charImg = new Image();
       charImg.src = "https://www.java2s.com/style/demo/Google-Chrome.png";
       function Character(x, y, speed, TilesPos, TilesRow) {
           this.x = x;
           this.y = y;
           this.w = 25;
           this.h = 25;
           this.sp = speed;
           this.Pos = TilesPos;
           this.Row = TilesRow;
           this.MaxTiles = 11;
       }
       Character.prototype.draw = function () {
           ctx.drawImage(charImg, this.Pos * this.w, this.w * this.Row, this.w, this.h, this.x, this.y, this.w, this.h);
       };
       var character = new Character(cw / 2, (ch - 25), 1, 1, 1);
       function Draw() {
           ctx.clearRect(0, 0, cw, ch);
           if (charImg.complete) {
               character.draw();
           }
       }
       function Update() {
       }
       setInterval(function () {
           Draw();
           Update();
       }, 1000 / fps);
   });
    });

      </script> 
   </head> 
   <body> 
      <canvas id="My_Canvas" style="width:400px;height:400px;border:1px solid black"></canvas>  
   </body>
</html>

Related Tutorials