【问题标题】:HTML5 Canvas - Drawing overlapping polygonsHTML5 Canvas - 绘制重叠多边形
【发布时间】:2014-10-03 23:42:03
【问题描述】:

所以,我有一个像这样的多边形绘制函数:

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/

【问题讨论】:

    标签: javascript html canvas drawing rendering


    【解决方案1】:

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

    使用destination-out compositing“擦除”组合多边形的中心:

    • 创建一个临时的离屏画布
    • 用双线宽描边多边形
    • 设置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);
    }
    

    【讨论】:

    • 有没有多个画布?
    • 是的。您可以先绘制轮廓,然后使用合成在轮廓“后面”绘制背景图像:jsfiddle.net/m1erickson/t595hbsn。此外,一个低效但完全数学的解决方案是(1)使用光线投射算法来计算每个多边形内的每个点,(2)使用行进正方形算法使用来自 # 的点来计算组合形状的外部1, (3) 从#2 中的点创建一条路径并在画布上绘制该路径
    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2013-11-01
    相关资源
    最近更新 更多