javascript - HTML5 Canvas合并成矩形形成新形状

标签 javascript html canvas

我有一个页面,您可以在上面绘制正方形。这些方 block 代表一个房间,所以你有一个方 block ,然后你在第一个方 block 上做另一个,然后两个会加入

看起来像这样 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}
    }
]

任何可以帮助我做到这一点的资源链接都会有很大帮助,谢谢

最佳答案

您可以使用合成在组合的矩形周围创建一个笔划。

  • 用笔画画出所有的矩形

  • 将合成设置为“目标输出”。这会导致新绘图“删除”两个重叠的现有绘图。

  • 填满你所有的直肠。这将删除组合矩形的轮廓以外的所有内容。

这是有效的,因为笔画一半在矩形边界内,一半在矩形边界外。当您删除组合矩形的内侧时,您会留下半外侧的笔触。

enter image description here

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

关于javascript - HTML5 Canvas合并成矩形形成新形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25670455/

相关文章:

javascript - 从 firebase 创建公共(public) REST API

html - 在 Bootstrap 3 中垂直居中 div 元素

javascript - 防止表单多次提交

javascript - 使用canvas自动加载图像的功能

css - HTML5 中的 canvas/video/audio 元素下方有 4px 的间隙

javascript - 当我将 SVG 内容绘制到 Canvas 时,SVG 被裁剪

javascript - 在 ng build angular 中运行严格编译

javascript - 类型错误 : Failed to execute 'fetch' on 'Window' : Invalid value

滚动时的 JavaScript 调整大小事件 - 移动设备

html - 当我在标题中给出边界有问题时?