The clearRect method removes whatever has been drawn in the specified rectangle.
The following code provides a demonstration.
<!DOCTYPE HTML> <html> <head> <title>Example</title> <style> canvas {border: thin solid black; margin: 4px} </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"); //w ww. ja v a2 s. co m let offset = 10; let size = 50; let count = 5; for (let i = 0; i < count; i++) { ctx.fillRect(i * (offset + size) + offset, offset, size, size); ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size, size, size); ctx.clearRect(i * (offset + size) + offset, offset + 5, size, size -10); } </script> </body> </html>
In this example, I use the clearRect method to clear an area of the canvas that has previously been drawn on by the fillRect method.