如何清除canvas元素中的多边形形状的区域? [英] How do you clear a polygon shaped region in a canvas element?

查看:1487
本文介绍了如何清除canvas元素中的多边形形状的区域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了clearRect函数,但没有看到多边形的等价物。我天真地尝试:

  ctx.fillStyle ='transparent'; 
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,50);
ctx.lineTo(50,100);
ctx.lineTo(0,90);
ctx.closePath();
ctx.fill();

但这只是绘制一个透明区域,并且对已经存在的内容没有影响。有没有办法清除canvas元素内的多边形区域?

解决方案

您可以使用


I've used the clearRect function, but didn't see an equivalent for polygons. I naively tried:

ctx.fillStyle = 'transparent';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

But that just draws a transparent region, and doesn't have an effect on what's already there. Is there a way to clear polygon regions inside of the canvas element?

解决方案

You can use compositing with the operation set to 'destination-out' for this:

ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100,50);
ctx.lineTo(50, 100);
ctx.lineTo(0, 90);
ctx.closePath();
ctx.fill();

Example:

Try it on jsFiddle

这篇关于如何清除canvas元素中的多边形形状的区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆