HTML5 Game - Canvas Image Resize

Resizing images

To resize an image, pass the width and height at which you want the image to be drawn.

The drawImage method with the arguments for resizing looks like this:

context.drawImage(image, x, y, width, height);  

Demo

ResultView the demo in separate window

<!DOCTYPE html>

<html>
  <head>
    <title>Manipulating images and video</title>
    <meta charset="utf-8">
    // ww  w  .j  a  v  a 2  s .  c om
    <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, 50, 33);
        });
      });
    </script>
  </head>
  
  <body>
    <canvas id="myCanvas" width="500" height="500">
      <!-- Insert fallback content here -->
    </canvas>
  </body>
</html>

Related Topics