HTML5 Canvas Reference - clearRect()








clearRect(x,y,width,height) method clears the specified area and makes it fully transparent using transparent black as the color starting at position x,y for width and height.

Browser compatibility

clearRect() Yes Yes Yes Yes Yes

JavaScript syntax

context.clearRect(x,y,width,height);

Parameter Values

Parameter Description
x/y The x/y-coordinate of the upper-left corner of the rectangle to clear
width The width of the rectangle to clear, in pixels
height The height of the rectangle to clear, in pixels




Example

The following code shows how to clear a rectangle.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "pink";
    ctx.fillRect(0, 0, 300, 150);<!--from ww  w. j a v  a  2s . co  m-->
    ctx.clearRect(20, 20, 100, 50);
</script>
</body>
</html>

The code above is rendered as follows: