HTML5 Game - Canvas Image Crop

Introduction

To crop an image, use drawImage() method with nine arguments:

  • the source image,
  • the (x, y) coordinate origin of the crop on the source image,
  • the width and height of the crop on the source image,
  • the (x, y) coordinate origin to draw the image on the canvas (the destination),
  • the width and height to draw the image on the canvas.

It has the following format:

context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);  

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    //from   w ww.j  ava 2s  . c o  m
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function() {  
        let canvas = $("#myCanvas");
        let context = canvas.get(0).getContext("2d");
        
        let image = new Image();
        image.src = "http://java2s.com/style/demo/jet2.png";
        $(image).load(function() {
          context.drawImage(image, 0, 0, 250, 250, 0, 0, 250, 250);
        });
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

We can resize the cropped image as you draw in onto the canvas, like so:

context.drawImage(image, 0, 0, 250, 250, 0, 0, 500, 500);  

Related Topics