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 <canvas>
element.
The clearRect()
method clears all pixels on the canvas in the given rectangle to transparent black.
The clearRect()
method accepts four parameters: clearRect(x,y,w,h)
.
x
- Horizontal coordinates that the cleared rectangle should start at. This is the number of pixels in from the left.
y
- Vertical coordinates that the cleared rectangle should start at. This is the number of pixels in from the top.
w
- Width of the rectangle.
h
- Height of the rectangle.
You can also use strokeStyle
along with the strokeRect()
method to create a rectangle outline.