HTML <canvas> Tag with the clearRect() Method
<canvas id="myCanvas" width="350" height="340"> <p>Fallback content for browsers that don't support the canvas tag.</p> </canvas> <script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // Paint large rectangle ctx.fillStyle = "GreenYellow"; ctx.fillRect (5, 5, 180, 100); // Clear a rectangle within larger rectangle ctx.clearRect(20, 20, 50, 70); </script>
The above example uses the
clearRect() method with the HTML
clearRect() method clears all pixels on the canvas in the given rectangle to transparent black.
clearRect() method accepts four parameters:
- Horizontal coordinates that the cleared rectangle should start at. This is the number of pixels in from the left.
- Vertical coordinates that the cleared rectangle should start at. This is the number of pixels in from the top.
- Width of the rectangle.
- Height of the rectangle.
You can also use
strokeStyle along with the
strokeRect() method to create a rectangle outline.