因此,我有一个多边形绘制函数,如下所示:
Polygon.prototype.draw = function(ctx) {
ctx.save();
ctx.beginPath();
var v = this.vertices[0]
ctx.moveTo(this.position.x + v.x, this.position.y + v.y);
var i = this.vertices.length;
while (i--) {
v = this.vertices[i]
ctx.lineTo(this.position.x + v.x, this.position.y + v.y);
}
ctx.strokeStyle = "#000";
ctx.stroke();
ctx.closePath()
ctx.restore();
}下面是重叠的两个多边形的绘制方式:

但如果它们重叠,我希望它们画成这样:

请注意,我对多边形进行了描边,因此我还希望保持画布背景图像。
另外,我想让它的工作超过2个多边形。
有什么好办法做到这一点吗?
小提琴:http://jsfiddle.net/k0cef75t/
发布于 2014-08-12 00:31:01
这里是使用合成的一种方法。
使用目标输出合成来“擦除”组合多边形的中心:
lineWidth
globalCompositeOperation="destination-out"

示例代码和演示:http://jsfiddle.net/m1erickson/8vrj8r2g/
onscreenContext.drawImage(strokeCombinedShapes(shapes), 40, 30);
function strokeCombinedShapes(shapes){
// ctx1 is the context of the off-screen canvas
ctx1.clearRect(0,0,canvas.width,canvas.height);
ctx1.save();
// stroke the polygons
for(var i=0;i<shapes.length;i++){
var pts=shapes[i];
ctx1.beginPath();
ctx1.moveTo(pts[0].x,pts[0].y);
for(var j=1;j<pts.length;j++){
ctx1.lineTo(pts[j].x,pts[j].y);
}
ctx1.closePath();
ctx1.lineWidth=2;
ctx1.stroke();
}
// set all new drawings to "erase" current drawings
ctx1.globalCompositeOperation="destination-out";
// fill the polygons
// this causes the insides of the polygons to be "erased"
for(var i=0;i<shapes.length;i++){
var pts=shapes[i];
ctx1.beginPath();
ctx1.moveTo(pts[0].x,pts[0].y);
for(var j=1;j<pts.length;j++){
ctx1.lineTo(pts[j].x,pts[j].y);
}
ctx1.closePath();
ctx1.fill();
}
ctx1.restore();
return(canvas1);
}https://stackoverflow.com/questions/25238297
复制相似问题