javascripthtmlcanvasglobalcompositeoperation

How do I cut/clip a shape and reveal the shape behind it?


So far I got this: http://jsfiddle.net/Lt7VN/

enter image description here

But it cuts/clips both the red and black rects while I want it to just cut the black rect, how would I go about doing that?

context.beginPath();

context.rect(20,20,160,200);
context.fillStyle = "red";
context.fill();

context.beginPath();
context.rect(20,20,150,100);
context.fillStyle = "black";
context.fill();

context.globalCompositeOperation = "destination-out";

context.beginPath();
context.arc(100, 100, 50, 0, 2*Math.PI);
context.fill();

Solution

  • You can do this on 1 canvas using compositing.

    enter image description here

    Here's code and a Fiddle: http://jsfiddle.net/m1erickson/F4dp3/

    <!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 context=canvas.getContext("2d");
    
        context.save();
    
        context.beginPath();
        context.rect(20,20,150,100);
        context.fillStyle = "black";
        context.fill();
    
        context.globalCompositeOperation = "destination-out";
    
        context.beginPath();
        context.arc(100, 100, 50, 0, 2*Math.PI);
        context.fill();
    
        context.globalCompositeOperation = "destination-over";
    
        context.beginPath();
        context.rect(20,20,160,200);
        context.fillStyle = "red";
        context.fill();
    
        context.restore();
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <canvas id="canvas" width=300 height=300></canvas>
    </body>
    </html>