HTML5 Game - Drawing Part of an Image

Introduction

While drawing images on a canvas we can just draw a portion of the source image instead of the entire image.

To do this image cropping, use the drawImage() method that takes the coordinates and dimensions of the image slice.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
   <script src="https://code.jquery.com/jquery-2.1.3.js"></script> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*ww  w  .  j  a  v  a 2 s .  c  om*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
       let img = new Image(); 
       $(img).load(function () { 
           context.drawImage(img, 0,0,200,40,0, 0, canvas.width/2 , canvas.height/2); 
       }); 
       img.src = "http://java2s.com/style/download.png"; 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

The drawImage() method we used takes four more parameters.

The two parameters after the image parameter indicate the x and y coordinates (0,0) of the source image at which cropping should begin.

The next two parameters indicate the width (200px) and height (40px) of the region from the source image.

Related Topic