javascript - HTML5 Canvas - 绘制重叠的多边形

标签 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--) {
        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();
}

这是如何绘制两个重叠的多边形:

Bad

但我希望它们(如果它们重叠)像这样绘制:

Good

请注意,我描画了多边形,因此我也想保留 Canvas 背景图像。

另外,我想让它也适用于 2 个以上的多边形。

有什么好的方法吗?

fiddle :http://jsfiddle.net/k0cef75t/

最佳答案

这是使用合成的一种方法。

使用目的地输出合成来“删除”组合多边形的中心:

  • 创建临时的屏幕外 Canvas
  • 用双倍线宽描边多边形
  • 设置globalCompositeOperation="destination-out"
  • 填充多边形(这将“删除”多边形的内部 - 只留下外部描边)
  • 在屏幕 Canvas 上绘制临时 Canvas

enter image description here

示例代码和演示: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/

相关文章:

javascript - html5 音频添加事件处理程序

javascript - 更改用悬停切换的 Canvas 上的不透明度

javascript - Jquery replacewith 无法正常工作

html - 标签未在表格单元格中腾出空间

javascript - RactiveJS:数据绑定(bind)文本区域导致 "cannot call removeChild with null"

HTML CSS3/Canvas 图像失真

javascript - 在 Canvas 中调整图像大小以保持分辨率

javascript - Socket.io 按钮监听器无法在移动设备上工作

javascript - 如果不使用像 three.js 这样的库,我将如何在 webgl 中进行环境反射?

javascript - 显示点击菜单项