简体   繁体   中英

How can I crop an image using only Javascript?

Is there anyway I can crop an image using raw javascript? I want to be able to have a function that takes an image (html tag or source or whatever) with a certain width, height, offsetX and offsetY and it create a image of the portion specified.

I am not that familiar with HTML5 canvas and the like but I need to support older browsers, so that's not even an option (it sucks I know).

I hope this is clear. Thanks.

If all you need is to display a portion 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 sending the data plus cropping values to a server which returns the cropped image.

Often, it's enough to set the limits for rendering by using CSS styles to make the image appear cropped.

Instead of an img , use a div . Assign the desired size to the div . Set the property background to -x -y url('...url-of-your-image...') no-repeat

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

Try with this:

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'
  });
}

The problem: needs Jquery, and probably the solution works in IE8+.... do you need for IE6+?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM