How to fill the ‘opposite’ shape on canvas?

Draw the black shape in the OP– that is, draw a rectangle with a circle cut out of the middle.

First call beginPath(); then draw the circle clockwise; then draw the rectangle counter-clockwise (or vice versa); and finally fill().

var ctx = $('#cv').get(0).getContext('2d');

ctx.fillStyle = "grey";
ctx.beginPath();
ctx.arc(200, 200, 100, 0, 2 * Math.PI);
ctx.rect(400, 0, -400, 400);
ctx.fill();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="400" height="400" id="cv"></canvas>

It might not be obvious from most of the documentation out there but you can combine multiple subpaths in a single fill(), stroke() or clip() operation. To make a hole in a shape, you just draw the shape of the hole in the opposite direction. The beginPath() method resets the current path. For fill() and clip(), Canvas uses the non-zero winding number rule– if you read up on that it should become clearer.

Leave a Comment

tech