HTML5 Canvas: Cropping an image

Using the drawImage method, we can have the image cropped.

The cropping properties are the start X and Y positions in the image and the width and height of the cropping frame.

Syntax:

ontext.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>Codecrawl.com: Cropping an image</title>
    <style>
        canvas {
            border: 1px solid #000;
        }
    </style>
</head>
<body>
<canvas id='canvas' width='640' height='480'></canvas>
<script>
    var canvas = document.getElementById('canvas').getContext('2d');
    var canvasImage = new Image();
    function cropImage() {
        canvas.drawImage(canvasImage,
                0, // position X inside the crop
                0, // position Y inside the crop
                457, // source image width
                343, // source image height
                110, //crop position X
                110, //crop position Y
                250, //crop width
                250 //crop height
        );
    }
    canvasImage.addEventListener('load', cropImage, false);
    canvasImage.src = 'https://codecrawl.com/code/images/ushuaia.jpg';
</script>
</body>
</html>

The original jpg image without cropping is located in this link.

 

Series Navigation<< HTML5 Canvas: Drawing an image with drawImage
HTML5 Canvas: Using an image to fill the canvas background >>