HTML Canvas Image Crop

Introduction

We can add six more parameters to the drawImage() method to crop an image:

context.drawImage(imageObj,//  w  w  w.j  av a 2s. c  o  m
                  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.

If you don't intend to scale a cropped image, then destWidth equals sourceWidth and destHeight equals sourceHeight.

View in separate window

<!DOCTYPE HTML> 
<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                // w w  w. j ava2  s. co m
                var imageObj = new Image();
                imageObj.onload = function(){
          // source rectangular area
                    var sourceX = 550;
                    var sourceY = 300;
                    var sourceWidth = 300;
                    var sourceHeight = 214;
                    
          // destination image size and position
                    var destWidth = sourceWidth;
                    var destHeight = sourceHeight;
                    var destX = canvas.width / 2 - destWidth / 2;
                    var destY = canvas.height / 2 - destHeight / 2;
                    
                    context.drawImage(this, 
                                      sourceX, 
                                      sourceY, 
                                      sourceWidth, 
                                      sourceHeight, 
                                      destX, 
                                      destY, 
                                      destWidth, 
                                      destHeight);
                };
                imageObj.src = "image2.png";
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>



PreviousNext

Related