HTML5 Canvas: Cropping an image

This entry is part 16 of 17 in the series HTML5 Canvas

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.



<!DOCTYPE html>
<html lang='en'>
    <meta charset='utf-8'>
    <title> Cropping an image</title>
        canvas {
            border: 1px solid #000;
<canvas id='canvas' width='640' height='480'></canvas>
    var canvas = document.getElementById('canvas').getContext('2d');
    var canvasImage = new Image();
    function cropImage() {
                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 = '';

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 >>