01AutoMonkey
01AutoMonkey

Reputation: 2809

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();

Upvotes: 1

Views: 865

Answers (2)

markE
markE

Reputation: 105035

You can do this on 1 canvas using compositing.

  • draw the black rect
  • set compositing to destination-out which "erases"
  • draw the arc (which erases part of the black rect)
  • set compositing to destination-over which "draws behind"
  • draw the red rect (which fills in behind the arc-cut-rect.

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>

Upvotes: 1

achamney
achamney

Reputation: 16

Two canvases is the only way I believe http://jsfiddle.net/Lt7VN/2/

context1.globalCompositeOperation = 'destination-out';

context1.beginPath();
context1.arc(100, 100, 50, 0, 2*Math.PI);
context1.globalAlpha = 1.0;
context1.fill();

Upvotes: 0

Related Questions