HTML5 Game - Cropping an image with drawImage()

Introduction

In the following code, we'll crop out a section of an image and then draw the result onto the canvas.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                //  w ww  .j  a  va 2  s .co  m
                let imageObj = new Image();
                imageObj.onload = function(){
                    // source rectangular area
                    let sourceX = 50;
                    let sourceY = 00;
                    let sourceWidth = 30;
                    let sourceHeight = 24;
                        
                    // destination image size and position
                    let destWidth = sourceWidth;
                    let destHeight = sourceHeight;
                    let destX = canvas.width / 2 - destWidth / 2;
                    let destY = canvas.height / 2 - destHeight / 2;
                        
                    context.drawImage(this, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                };
                imageObj.src = "http://java2s.com/style/download.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

The code above uses the following drawImage() method:

Context.drawImage(imageObj,
                  sourceX,
                  sourceY,
                  sourceWidth, 
                  sourceHight,  
                  sourceHeight,
                  sourceHeight, 
                  destX, 
                  destY, 
                  destWidth, 
                  destHeight); 

sourceX and sourceY refer to the top-left corner of the cropped region in the source image.

sourceWidth and sourceHeight refer to the width and height of the cropped image from the source.

destX and destY refer to the position of the cropped image on the canvas.

destWidth and destHeight refer to the width and height of the resulting cropped image.

Related Topic