首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HTML5画布-绘制重叠多边形

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

Stack Overflow用户
提问于 2014-08-11 15:55:55
回答 1查看 451关注 0票数 2

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

代码语言:javascript
运行
复制
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/

EN

回答 1

Stack Overflow用户

发布于 2014-08-12 00:31:01

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

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

  • create a temporary offscreen canvas

lineWidth

  • globalCompositeOperation="destination-out"
  • the polygons (这将“擦除”多边形的内部--只留下屏幕画布上的外部画布

示例代码和演示:http://jsfiddle.net/m1erickson/8vrj8r2g/

代码语言:javascript
运行
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25238297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档