How to crop image using only Javascript?

Anyway, can I crop the image using raw javascript? I want to have a function that takes an image (html tag or source or something else) with a specific width, height, offsetX and offsetY and creates an image of the specified part.

I am not familiar with HTML5 canvas, etc., but I need to support older browsers, so it’s not even an option (this sucks, I know).

Hope this is clear. Thanks.

+4
source share
3 answers

If you need to display part of the image, use css clip: https://developer.mozilla.org/en/CSS/clip . Works in IE6 + even with JavaScript disabled.

If you need to physically crop the image and need IE6 support, then your options are Flash or send data and crop the values ​​to a server that returns the cropped image.

+4
source

Often, setting limits for rendering with CSS styles is enough to make the image appear cropped.

Use div instead of img . Set the desired div size. Set the background property to -x -y url('...url-of-your-image...') no-repeat

Replace x and y top / left offset you want to display.

+2
source

Try the following:

 function crop(img_id, crop_id, x, y, width, height) { $(crop_id).update('<img id="' + crop_id + '_img" src="' + $(img_id).getAttribute('src') + '" style="display:none" />'); var scale_x = $(crop_id).getWidth() / width; var scale_y = $(crop_id).getHeight() / height; $(crop_id).setStyle({ position: 'relative', overflow: 'hidden' }); $(crop_id + '_img').setStyle({ position: 'absolute', display: 'block', left: (-x * scale_x) + 'px', top: (-y * scale_y) + 'px', width: ($(img_id).getWidth() * scale_x) + 'px', height: ($(img_id).getHeight() * scale_y) + 'px' }); } 

Problem: JQuery is required, and the solution probably works in IE8 + .... do you need it for IE6 +?

+1
source

All Articles