开发者

HTML5 globalCompositeOperation vs clip

I have a large source image and I want to display a small section of it inside a circle, with leaving the part of the canvas outside of the circle transparent.

The Mozilla guide to Compositing with开发者_开发知识库 HTML5 covers two topics: globalCompositeOperation and clip. It looks like both of these will let me do what I want, so I'm wondering what the drawbacks are of each, and which I should use.

I could set globalCompositeOperation to source-atop (or source-in, but that seems buggy in WebKit). Then have the destination canvas be transparent with a black circle, and simply draw the source image over that. This will ensure that only the circle part will be filled in.

Or, I could draw a circular path and use clip to define a clipping region, then draw the source image over that, which should also ensure only the circle part will be filled in (in fact, Mozilla's page above even has an example of doing pretty much that with stars).

  1. Will both of these techniques work as I say they will, or am I missing something?
  2. If so, are there any major gotchas with either of these techniques which makes one clearly better than the other?
  3. If not, which one has better performance in general?

I would (purely speculatively) imagine the globalCompositeOperation would have better performance, since it is applying the operation on a per-pixel level, whereas the clip operation needs to do polygon intersection. But that's just a hunch.


As of March, globalCompositeOperation did not work the same on all browsers.

Clip does... except the anti-aliasing, actually, which is sadly different per browser.

In my opinion the appropriate thing to do here is use clip. Using source-atop may work for your very specific situation, but it isn't very extensible as you described it. If you ever want to change any of it, like say have a background behind your circle, you'll run into trouble if you do it the globalComposite way.

And the tests are in: Clip is faster in every browser I tested, and massively faster in Firefox. See the results or try for yourself here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜