Copy and crop images in Javascript

前端 未结 4 1269
死守一世寂寞
死守一世寂寞 2020-12-15 00:57

I\'m trying to create a small 2D game in Javascript/Canvas which consists of several animated sprites. I\'d like to cut down on the number of HTTP requests, so I combined ea

相关标签:
4条回答
  • 2020-12-15 01:02

    Just load the image in an img tag with style attribute display set to hidden. Then crop the image on an off screen canvas, then write that off screen canvas to your main canvas as required.

    0 讨论(0)
  • 2020-12-15 01:08

    Have a look at Pixastic, specifically http://www.pixastic.com/lib/docs/actions/crop.

    0 讨论(0)
  • 2020-12-15 01:08

    If you don't want to use canvas or 3rd party library, you could add the image to a div (with "overflow: hidden") of the size of the cropped version, and giving the image negative left and top margins.
    Each one will carry the whole image around, but will just display a portion of it, which may -- or may not -- impact performance. I believe you may have to give the div element a position:relative as well to make IE happy.

    Alternatively you could assign the image as a background of the div, and specify the backgroundPosition. I seem to remember this didn't work for something I did once, not sure why. (I think it had to do with opacity)

    0 讨论(0)
  • 2020-12-15 01:20

    The HTML5 Canvas API provides a method called drawImage which allows you to crop the input image.

    context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
    

    alt text

    For more information see the spec (that image is taken directly from the spec):

    http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#images

    0 讨论(0)
提交回复
热议问题