canvas清除已绘制的图形

HTML5 Canvas 清除圆形、不规则区域

原文地址:HTML5 Canvas 清除圆形、不规则区域

  1. clearRect

默认 Canvas Api 只提供了清除矩形区域的接口 clearRect(),但有时候需要清除圆形或其他特殊形状的区域。

  1. ctx.globalCompositeOperation

ctx.globalCompositeOperation 提供了多种色彩合成模式,其中 destination-out 能够完成清除效果

  • source-over

这是默认设置,并在现有画布上下文之上绘制新图形。

  • destination-out

现有内容保持在新图形不重叠的地方。(优点就是不会清空整个画布,会保留之前以及绘制的部分)

CanvasRenderingContext2D.prototype.clearArc = function(x, y, radius, startAngle, endAngle, anticlockwise) {
    this.beginPath();
    this.globalCompositeOperation = 'destination-out';
    this.fillStyle = 'black';
    // 绘制新图形
    this.arc(x, y, radius, startAngle, endAngle, anticlockwise);
    // 参数分别是:圆心横坐标、纵坐标、半径、开始的角度、结束的角度、是否逆时针
    this.fill();
    this.closePath();
};
  1. 通过清空画布也可以实现
// canvas每当高度或宽度被重设时,画布内容就会被清空,所以会导致之前画的圆都被删除
      function clearCanves(canvas, width, height) {
        canvas.height = height;
        canvas.width = width;
      }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容