html5 clip,clipping - How can I clip INSIDE a shape in HTML5 canvas? - Stack Overflow

Available options

For irregular shapes you can use two techniques:

Composite mode

Clipping

IMHO the better choice to use the actual clipping mode or the composite mode destination-out.

As markE says in his answer xor is available too, but xor only inverts alpha pixels and doesn't remove the RGB pixels. This works for solid images with no transparency, but where you have existing pixels with transparency these might give you the opposite effect (becoming visible) or if you later use xor mode with something else drawn on top the "clipped" area will show again.

Clipping

By using clipping you can simply use clearRect to clear the area defined by the path.

Example:

/// save context for clipping

ctx.save();

/// create path

ctx.beginPath();

ctx.arc(x, y, radius, 0, 2 * Math.PI);

ctx.closePath();

/// set clipping mask based on shape

ctx.clip();

/// clear anything inside it

ctx.clearRect(0, 0, offset, offset);

/// remove clipping mask

ctx.restore();

Source image: an image that has partial semi-transparent pixels and full transparent where the white from background comes through -

EiuHB.png

Result:

We punched a hole in it and the background shows through:

06qss.png

Composite mode: destination-out

Using composite mode destination-out will clear the pixels as with clipping:

ctx.beginPath();

ctx.arc(offset * 0.5, offset * 0.5, offset * 0.3, 0, 2 * Math.PI);

ctx.closePath();

/// set composite mode

ctx.globalCompositeOperation = 'destination-out';

ctx.fill();

/// reset composite mode to default

ctx.globalCompositeOperation = 'source-over';

Result:

06qss.png

Same as with clipping as destination-out removes the pixels.

Composite mode: xor

Using xor in this case where there exists transparent pixels (see online example here):

k8LZf.png

Only the alpha values was inverted. As we don't have solid pixels the alpha won't go from 255 to 0 (255 - 255) but 255 - actual value which result in non-cleared background using this mode.

(if you draw a second time with the same mode the "removed" pixels will be restored so this can be utilized in other ways).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值