javascript

How can I crop an area of an image using JavaScript?


How can I crop an area of an image using JavaScript? As I have read, I must use a canvas to project the image on it.

With the following code I am cutting an area of an image, but the size of the cut area is not the indicated one.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();

imageObj.onload = function() {

    // draw cropped image
    var sourceX = 0;
    var sourceY = 0;
    var sourceWidth = 500;
    var sourceHeight = 150;
    var destWidth = sourceWidth;
    var destHeight = sourceHeight;
    var destX = canvas.width / 2 - destWidth / 2;
    var destY = canvas.height / 2 - destHeight / 2;
    
    context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);

};
imageObj.src = 'https://i.sstatic.net/GPezBEtQ.jpg';
<canvas id="myCanvas" style="border:1px solid red"></canvas>

I am trying to represent in this image what I want to do.

enter image description here

My main problem is that the canvas does not adapt to the size of the cropped image and the final height (sourceHeight) and width (sourceWidth). They are not the ones I specified

How can I fix it?


Solution

  • The problem

    Your source "width" is the same width as the image.

    The solution

    When using context.drawImage with 9 arguments, think of it like a cut and paste.

    You want to "cut" the outline in red, and "paste" it to your new - centered - location.

    You want to "cut" all the way up to the half way point of the source. So you need to select all the way up to the half way point of the image.

    I also suggest maybe changing the variable name from source to crop (cropX, cropWidth, etc) to better reflect its purpose, as it is not really the width of the source anymore.

    If you want the image to fill the entire canvas, paste it with the canvas' width and height at 0, 0:

    context.drawImage(imageObj, cropX, cropY, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height);;
    

    The code

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image();
    
    imageObj.onload = function() {
        // crop from 0,0, to 250,150
        var cropX = 0;
        var cropY = 0;
        var cropWidth = 250;
        var cropHeight = 150;
    
        //resize our canvas to match the size of the cropped area
        canvas.style.width = cropWidth;
        canvas.style.height = cropHeight;
    
        //fill canvas with cropped image
        context.drawImage(imageObj, cropX, cropY, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height);
    };
    imageObj.src = 'https://i.sstatic.net/GPezBEtQ.jpg';
    <canvas id="myCanvas" style="border:1px solid red"></canvas>