Canvas clearRect: HTML5


Rectangle is the only primitive type supported by canvas.

It has 3 functions:
strokeRect(x, y, w, h);
fillRect(x, y, w, h);
clearRect(x, y, w, h);

In our previous video tutorials we’ve seen using strokeRect and fillRect methods. In this short video tutorial, we’re illustrating clearRect() method.

clearRect method erases the given rectangle and makes the area fully transparent.

index.html and myStyle.css files are kept same as illustrated in previous video tutorial: Canvas State: HTML5

JavaScript file
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
 
context.fillStyle = "red";
context.fillRect(10, 10, 75, 75);
 
context.fillStyle = "blue";
context.fillRect(90, 10, 75, 75);
 
context.clearRect(5, 40, 200, 40)
}
}

Here we first draw 2 rectangles: red and blue.
Next clear part of these two rectangles using clearRect method.

We start clearRect() from 5px x-axis, and 40px y-axis; with a width of 200px, so that it covers both red and blue rectangles.

Canvas clearRect: HTML5



YouTube Link: https://www.youtube.com/watch?v=W1W5LEGeqjI [Watch the Video In Full Screen.]



Advantages of clearRect() method may not seem obvious at first, but will be helpful in game development – to draw transparent paths between your drawings/graphics.

Leave a Reply

Your email address will not be published. Required fields are marked *