所以,我有一个像这样的多边形绘制函数:
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();
}
这是如何绘制两个重叠的多边形:
但我希望它们(如果它们重叠)像这样绘制:
请注意,我描画了多边形,因此我也想保留 Canvas 背景图像。
另外,我想让它也适用于 2 个以上的多边形。
有什么好的方法吗?
fiddle :http://jsfiddle.net/k0cef75t/
最佳答案
这是使用合成的一种方法。
使用目的地输出合成来“删除”组合多边形的中心:
- 创建临时的屏幕外 Canvas
- 用双倍线宽描边多边形
- 设置
globalCompositeOperation="destination-out"
- 填充多边形(这将“删除”多边形的内部 - 只留下外部描边)
- 在屏幕 Canvas 上绘制临时 Canvas
示例代码和演示: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);
}
关于javascript - HTML5 Canvas - 绘制重叠的多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238297/