We can use the clip method to clip a region.
Name | Description | Returns |
---|---|---|
clip() | Creates a new clipping region | void |
Once we define a clipping region, only paths that occur inside of the region are shown on the screen.
The example draws a rectangle that fills the canvas, creates a smaller clipping region and then draws another canvas-filling rectangle.
Only the part of the second rectangle which fits within the clipping region is drawn.
<!DOCTYPE HTML> <html> <head> <title>Example</title> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="500" height="140"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "yellow"; ctx.beginPath();/*from w ww. j av a2s. c o m*/ ctx.rect(0, 0, 500, 140); ctx.fill(); ctx.beginPath(); ctx.rect(100, 20, 300, 100); ctx.clip(); ctx.fillStyle = "red"; ctx.beginPath(); ctx.rect(0, 0, 500, 140); ctx.fill(); </script> </body> </html>