crop image canvas 1

crop image canvas

var image = new Image(),
    canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = function(){
    ctx.drawImage(image,
        70, 20,   // Start at 70/20 pixels from the left and the top of the image (crop),
        50, 50,   // "Get" a `50 * 50` (w * h) area from the source image (crop),
        0, 0,     // Place the result at 0, 0 in the canvas,
        100, 100); // With as width / height: 100 * 100 (scale)
}

Here is what the above code is Doing:
1. Create a new Image object and load the image.
2. When the image is loaded, draw it on the canvas.
3. Start at 70/20 pixels from the left and the top of the image (crop).
4. Get a 50 * 50 area from the source image (crop).
5. Place the result at 0, 0 in the canvas.
6. With as width / height: 100 * 100 (scale).

Similar Posts