clearRect() Method - Javascript Canvas Reference

Javascript examples for Canvas Reference:clearRect


The clearRect() method clears the pixels within a rectangle.

JavaScript syntax

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

Parameter Values

Parameter Description
x The x-coordinate of the rectangle upper-left corner
y The y-coordinate of the rectangle upper-left corner
width The width of the rectangle in pixels
heightThe height of the rectangle in pixels


Clear a rectangle within a given rectangle:


Demo Code

ResultView the demo in separate window

<!DOCTYPE html>

<canvas id="myCanvas" width="300" height="250" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 300, 150);//from  www . j  a va 2s .  com
ctx.clearRect(20, 20, 100, 150);


Related Tutorials