HTML5 Canvas合并为矩形以形成新形状

Ben*_*Ben 3 javascript html5 canvas

我有一个页面,你可以在上面绘制正方形.方块将代表一个房间,所以你有一个方格,然后你在第一个方格上再做一个,然后两个将加入

它看起来像这样 http://puu.sh/bllo7/95e2112d79.png

http://jsfiddle.net/bLenxexL/这样的功能

我需要弄清楚如何让它们正方形来制作另一个看起来像上图右侧图像的形状.

如果这有帮助,则方格信息points以此格式存储

[
    {
        start: {x: 312, y: 164}, 
        end: {x: 734, y: 371}
    },
    {
        start: {x: 696, y: 304}, 
        end: {x: 1060, y: 561}
    }
]
Run Code Online (Sandbox Code Playgroud)

任何有助于我这样做的资源链接都会对你有所帮助

mar*_*rkE 7

您可以使用合成在组合矩形周围创建单个笔划.

  • 用笔划绘制所有矩形

  • 将compositing设置为'destination-out'.这导致新图纸"擦除"两者重叠的现有图纸.

  • 填写你所有的rects.除了组合矩形的轮廓之外,这将删除所有内容.

这是有效的,因为笔划是在矩形边框的半边和半边之外绘制的.当您擦除组合矩形的内部时,您将留下半外侧笔划.

在此输入图像描述

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

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // draw all rects with strokes
    ctx.strokeRect(20,20,100,200);
    ctx.strokeRect(90,110,75,50);

    // set compositing to erase existing drawings 
    // new drawings will erase existing drawings where the two overlap
    ctx.globalCompositeOperation='destination-out';

    // fill all rects
    // This "erases" all but the outline stroke
    ctx.fillRect(20,20,100,200);
    ctx.fillRect(90,110,75,50);

    // reset compositing to its default mode
    ctx.globalCompositeOperation='source-over';

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)