可以使用合成和临时画布。类似的东西:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var tempCanvas = document.getElementById('tempCanvas');
var tempContext = tempCanvas.getContext('2d');
tempContext.save();
// clear temp context
tempContext.clearRect(0, 0, canvas.width, canvas.height);
// draw all rects with strokes
tempContext.beginPath();
tempContext.strokeStyle='red';
tempContext.lineWidth=3;
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false);
tempContext.rect(20,150,100,200);
tempContext.stroke();
// set compositing to erase existing drawings
// where the new drawings are drawn
tempContext.globalCompositeOperation='destination-out';
// fill all rects
// This "erases" all but the outline stroke
tempContext.beginPath();
tempContext.fillStyle='blue';
tempContext.arc(100, 100, 60, 0, 2 * Math.PI, false);
tempContext.rect(20,150,100,200);
tempContext.fill();
// draw outlines from tempcanvas into canvas
ctx.drawImage(tempCanvas, 0, 0);
// draw into canvas
ctx.beginPath();
ctx.fillStyle='green';
ctx.globalAlpha = 0.2;
ctx.rect(20,150,100,200);
ctx.arc(100, 100, 60, 0, 2 * Math.PI, false);
ctx.fill();
tempContext.restore();
而且一个的jsfiddle:https://jsfiddle.net/EvaF/8to68dtd/2/
我明白了,世界上没有其他办法合并形状?你必须画出你想要的。干杯。 – fes 2011-04-08 14:18:09
技术上还有其他方法可以达到同样的效果。 你可以用黑色填充Rect和Circle,然后在它们上面填充一个2像素的小矩形和圆。这将达到相同的效果(我认为),根本不使用任何路径。但是如果你想使用路径,你不能相交它们,你必须画出确切的东西。 – 2011-04-08 17:30:29