美文网首页
小程序 canvas上clip不起作用,使用clearRect清

小程序 canvas上clip不起作用,使用clearRect清

作者: 小雨hahaha | 来源:发表于2019-03-05 15:38 被阅读0次

我把canvas背景色设置成了透明色,在上面先用fillRect画了一个白色画布,在画布上用clip想切一个圆形,结果怎么切都切不了,不起作用,后来用clearRect方式做出来,思路是用很多矩形堆积出圆形

// 绘制底层白色画布
    ctx.beginPath();
    ctx.fillStyle='white';
    ctx.fillRect(0, 0, ctxWidth, ctxHeight);
    ctx.closePath();

用了是上面的画了背景之后,再clip就不起作用,但是clearRect可以起作用,方法如下:

/**
 * canvas绘图相关
 * (x,y)为要清除的圆的圆心,r为半径,cxt为context
 *  用clearRect方法清除canvas上不能用clip剪切的圆形
 */
function clearArcFun(x, y, r, cxt) {
  var stepClear = 0.1;//这是定义精度 
  clearArc(x, y, r);
  function clearArc(x, y, radius) {
    var calcWidth = radius - stepClear;
    var calcHeight = Math.sqrt(radius * radius - calcWidth * calcWidth);

    var posX = x - calcWidth;
    var posY = y - calcHeight;

    var widthX = 2 * calcWidth;
    var heightY = 2 * calcHeight;

    if (stepClear <= radius) {
      cxt.clearRect(posX, posY, widthX, heightY);
      stepClear += 0.1;
      clearArc(x, y, radius);
    }
  }
}

相关文章

网友评论

      本文标题:小程序 canvas上clip不起作用,使用clearRect清

      本文链接:https://www.haomeiwen.com/subject/bacouqtx.html