Search code examples
javascriptimagescalecrop

Javascript crop and scale image to be 300 pixel


I want to know how we can scale and crop an image in Javascript. I want to scale it down to 300x300px and crop it a little. Do you have any suggestions ? I have the following code :

function cropImage(imagePath, newX, newY, newWidth, newHeight) {
//create an image object from the path
var img = document.createElement('img');
img.src = "data:image/png;base64,"+imagePath;
    
//alert(img.width);
//alert(img.height);
//initialize the canvas object
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');



    //set the canvas size to the new width and height
    canvas.width = 300;
    canvas.height = 300;
     
    //draw the image
    
        ctx.drawImage(img, newX, 75, 300, 300, 0, 0, 300, 300);
    variables.imageCrop = canvas.toDataURL();}

Thank you !


Solution

  • Try it:

    And learn more about .drawImage()

    function cropImage(imagePath, leftRight, topBottom, newWidth, newHeight) {
      const img = document.createElement('img');
      img.src = imagePath;
    
      const canvas = document.createElement('canvas');
        document.body.appendChild(canvas);
      const ctx = canvas.getContext('2d');
    
      img.addEventListener('load', function() {
      
      //Set your canvas size as your choice
      //here i just scaled by 10 with original dimension
        canvas.width = img.naturalWidth*10;
        canvas.height = img.naturalHeight*10;
        
        const cropLeft = leftRight[0];
        const cropRight = img.naturalWidth - leftRight[0] - leftRight[1];
        
        const cropTop = topBottom[0];
        const cropBottom = img.naturalHeight - topBottom[0] - topBottom[1];
        ctx.drawImage(
        img, 
        cropLeft,cropTop,
        cropRight, cropBottom,
        0,0, //here you can control placement of cropped image from left and top, by default it stays in 0,0 meaning the top left corner of the canvas
        newWidth,newHeight //new width and height of cropped image
        );
      });
    }
    
    //Size of this image is 100x100 px
    const img = "https://dummyimage.com/100.png/09f/fff";
    
    //here [10,10] meaning crop 10px from left and 10px from right
    //here [20,20] meaning crop 20px from top and 20px from bottom
    cropImage(img,[10,10],[20,20], 100, 100);