Skip to content Skip to sidebar Skip to footer

HTML5 Canvas Merging To Rectangles To Form A New Shape

I have a page that you will be able to draw squares on it. The squares will represent a room, so you have one square, then you make another over the first square and then two will

Solution 1:

You can use compositing to create a single stroke around your combined rectangles.

  • draw all your rectangles with strokes

  • set compositing to 'destination-out'. This causes new drawings to "erase" existing drawings where the two overlap.

  • fill all your rects. This erases all but the outline of the combined rectangles.

This works because strokes are drawn half-inside & half-outside the border of rectangles. When you erase the inside of the combined rectangles you are left with the half-outside strokes.

enter image description here

Example code and a Demo: http://jsfiddle.net/m1erickson/m5jg92wd/

<!doctype html>
<html>
<head>
<link  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>

Post a Comment for "HTML5 Canvas Merging To Rectangles To Form A New Shape"