Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript HTML5画布-绘制重叠多边形_Javascript_Html_Canvas_Drawing_Rendering - Fatal编程技术网

Javascript HTML5画布-绘制重叠多边形

Javascript HTML5画布-绘制重叠多边形,javascript,html,canvas,drawing,rendering,Javascript,Html,Canvas,Drawing,Rendering,因此,我有一个多边形绘制功能,如下所示: 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--) {

因此,我有一个多边形绘制功能,如下所示:

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();
}
这是绘制重叠的两个多边形的方式:

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

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个多边形了

有什么好办法吗


小提琴:这里有一种使用合成的方法。

使用目标输出合成“擦除”组合多边形的中心:

  • 创建临时屏幕外画布
  • 使用双线宽绘制多边形
  • 设置
    globalCompositeOperation=“目的地输出”
  • 填充多边形(这将“擦除”多边形的内部,只留下外部笔划)
  • drawImage屏幕画布上的临时画布

示例代码和演示:

onscreenContext.drawImage(strokeCombinedShapes,40,30);
函数strokeCombinedShapes(形状){
//ctx1是屏幕外画布的上下文
ctx1.clearRect(0,0,canvas.width,canvas.height);
ctx1.save();
//划多边形

对于(var i=0;iIs是否有多张画布?是的。您可以先绘制轮廓,然后使用合成在轮廓后面绘制背景图像:。此外,一个效率低下但完全数学化的解决方案是:(1)使用光线投射算法计算每个多边形内的每个点,(2)使用marching squares算法,使用#1中的点计算组合形状的外部,(3)从#2中的点创建路径,并在画布上绘制该路径