0

我正在努力实现以下目标:

在画布上绘制了许多同心圆(或环)。每个圆圈都有一个“洞”,因此在其后面绘制的较小圆圈是部分可见的。每一帧(我们使用 window.requestAnimationFrame 来渲染)每个圆/形状/环的半径都会略微增加。

此处的图像中描绘了具有两个环的场景。

示例图片

编码:

function draw() {
    drawBgr();
    for (var i = 0, len = rings.length; i < len; i++) {
        rings[i].draw();
    }
}

function drawBgr() {
    context.globalCompositeOperation = "source-over";
    context.clearRect(0, 0, WIDTH, HEIGHT);
    context.rect(0, 0, WIDTH, HEIGHT);
    context.fillStyle = '#FFFFFF';
    context.fill();
}

function squareRing(ring) { //called by rings[i].draw();
    context.globalCompositeOperation = "source-over";

    context.fillRect(ring.centerX - ring.radius / 2, ring.centerY - ring.radius / 2, ring.radius, ring.radius);
    context.globalCompositeOperation = "source-out";

    context.beginPath();
    context.arc(CENTER_X, CENTER_Y, ring.radius, 0, 2 * Math.PI, false);
    //context.lineWidth = RING_MAX_LINE_WIDTH * (ring.radius / MAX_SIDE);
    context.fillStyle = '#000000';
    context.fill();
    context.globalCompositeOperation = "source-over";

}
  1. 这里到底有什么问题?我在绘制圆圈之前调用 clearRect 。请参阅“我实际得到的”图像。这是在多个帧上绘制 SINGLE RING 的结果。我不应该得到任何与中间有一个空心正方形的黑色圆圈不同的东西。(请注意,半径每帧都在增加。)

  2. 我确实意识到切换 globalCompositeOperation 可能不足以达到我想要的效果。如何在画布上绘制的对象中绘制一个“洞”而不擦除我要修改的对象下方“洞”中的所有内容?

是我用作 globalCompositeOperation 值参考的教程。

我正在使用 Firefox 28.0。

4

1 回答 1

0

我不会尝试使用 globalCompositeOperation,因为我发现很难弄清楚几次迭代后会发生什么,如果之前没有清除画布则更难。

我更喜欢使用剪辑,这让我明白:

http://jsbin.com/guzubeze/1/edit?js,输出

在此处输入图像描述

那么,要在平局中建立一个“洞”,如何使用剪裁?
-->> 定义一个正向剪切子路径,在这个区域内,剪掉一个负向部分,这次使用顺时针的子路径:

在此处输入图像描述

剪裁必须用一条路径完成,因此不能使用 rect() :它每次都会开始一条路径,并且不允许选择顺时针 (:-)),因此您必须定义这两个函数来创建所需的子路径:

// clockwise sub-path of a rect
function rectPath(x,y,w,h) {
  ctx.moveTo(x,y);
  ctx.lineTo(x+w,y);
  ctx.lineTo(x+w,y+h);
  ctx.lineTo(x,y+h);
}

// counter-clockwise sub-path of a rect
function revRectPath(x,y,w,h) {
  ctx.moveTo(x,y);
  ctx.lineTo(x,y+h);
  ctx.lineTo(x+w,y+h);
  ctx.lineTo(x+w,y);  
}

然后你可以写你的绘图代码:

function drawShape(cx, cy, d, scale, rotation) {
  ctx.save();
  ctx.translate(cx,cy);
  scale = scale || 1;
  if (scale !=1) ctx.scale(scale, scale);
  rotation = rotation || 0;
  if (rotation) ctx.rotate(rotation);
  // clip with rectangular hole
  ctx.beginPath();
  var r=d/2; 
  rectPath(-r,-r, d, d);
  revRectPath(-0.25*r,-0.8*r, 0.5*r, 1.6*r);
  ctx.closePath();
  ctx.clip();
  ctx.beginPath();
  // we're clipped !
  ctx.arc(0,0, r, 0, 2*Math.PI);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}

编辑 :

为了记录,有一个更简单的方法来绘制所要求的方案:只画一个圆圈,然后在里面逆时针画一个矩形。您填充的将是矩形外的圆圈内的部分,这就是您想要的:

function drawTheThing(x,y,r) {
   ctx.beginPath();
   ctx.arc(x ,y, r, 0, 2*Math.PI);
   revRectPath(x-0.25*r, y-0.8*r, 0.5*r, 1.6*r);
   ctx.fill();
   ctx.closePath();
}

(我不张贴图片:它是一样的)。

如果您更改平局或者如果您想引入某种通用性,请根据您的需要使用第一个或第二个。如果以后不更改方案,则第二种解决方案更简单 => 更好。

于 2014-04-10T10:48:38.103 回答