可以通过使用globalCompositeOperation来完成。有多种方法可以绘制形状他们的自我,但这里是一个办法,导致这(两个
矩形圈在演示):
第1步:设置正常帆布
第2步:设置屏幕外的画布
更新不知道我怎么能错过显而易见的,但你当然可以只中风首先,然后用复合模式和填充来打一个整体 - 快得多(我猜想当我提出偏移重绘时,我的脑海中有图像)。
离屏画布的原因是,如果你在主画布上已经有背景的东西。如果我们打洞的话,这将被删除。如果无所不有没有问题画这一个单一的画布 - 更新代码:
/// some regions
var rect = [ [20, 20, 200, 200], [100, 100, 200,200] ],
/// ox = off-screen context
ox.strokeStyle = '#fff';
ox.lineWidth = 3 * 2; /// x2 as half will be gone when we punch hole
/// stroke outlines
for(; r = rect[i]; i++) {
o = r[2] * 0.5;
ox.beginPath();
ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI);
ox.stroke();
}
/// punch hole with composite mode and fill
ox.globalCompositeOperation = 'destination-out';
for(i = 0; r = rect[i]; i++) {
o = r[2] * 0.5;
ox.beginPath();
ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI);
ox.fill();
}
/// draw result to main canvas
/// ctx = main context, ocanvas = off-screen canvas
ctx.drawImage(ocanvas, 0, 0);
我会离开,因为它可以用于图像的旧代码,可以” t被抚摸 -
现在绘制形状填充到离屏画布。绘制您想要轮廓所在的颜色。
/// some regions
var rect = [ [20, 20, 200, 200], [100, 100, 200,200] ],
/// ox = off-screen canvas
ox.fillStyle = '#fff';
/// draw the array with circes
for(; r = rect[i]; i++) {
var o = r[2] * 0.5;
ox.beginPath(); //use this here - arcs are currently buggy
ox.arc(r[0] + o, r[1] + o, o, 0, 2 * Math.PI);
ox.fill(); //.. and here
}
现在将形状的缓存图像绘制回主画布。形状必须有轻微的在每个方向偏移绘制 - 这一步将创建轮廓:
/// ctx = main context, ocanvas = off-screen canvas
ctx.drawImage(ocanvas, -1, -1);
ctx.drawImage(ocanvas, 1, -1);
ctx.drawImage(ocanvas, 1, -1);
ctx.drawImage(ocanvas, 1, 1);
ctx.drawImage(ocanvas, -1, 1);
ctx.drawImage(ocanvas, 1, 1);
ctx.drawImage(ocanvas, -1, -1);
ctx.drawImage(ocanvas, -1, 1);
最后,我们冲在填充形状的“洞”,使之透明使用globalCompositeOperation +一个大纲在0战平最终偏移位置:
ctx.globalCompositeOperation = 'destination-out';
ctx.drawImage(ocanvas, 0, 0);
为了使边框较厚强制当您将图形绘制回主画布时,增加偏移量。