Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim an Image in Javascript

I've an image and I want to remove blank borders at the corner from it. How can I trim an Image in Javascript? Will be better whitout huge libraries. Any idea?


1 Answers

With the help of an "CanvasRenderingContext2D" object (canvas element), you can do what ever you want with your image. Just resize the canvas and use the drawImage() method:

function trimImage(img, posX, posY, recWidth, recHeight)
{
    var canvas = document.createElement('canvas');
    canvas.width = recWidth;
    canvas.height = recHeight;
    var context = canvas.getContext('2d');
    context.drawImage(img, -posX, -posY);
    img.parentNode.replaceChild(canvas, img);
}
window.addEventListener("DOMContentLoaded", function()
{
    var img = document.createElement('img');
    img.src = "image.png";
    document.body.appendChild(img);
    img.onload = function() { trimImage(img, 10, 5, img.width - 40, img.height - 80); }
});

The canvas element is an image. If you need a image tag, you can switch it back by using toDataURL() to get an src attribute.

replace

img.parentNode.replaceChild(canvas, img);

with

var newImg = document.createElement('img');
newImg.src = canvas.toDataURL();
img.parentNode.replaceChild(newImg, img);

I think a new image is necessary, to refire an onload event.

like image 104
Martin Wantke Avatar answered Oct 24 '25 11:10

Martin Wantke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!