Resetting the Canvas clearRect Function
The clearRect()
function
takes in the start x,y location and the width and height
to clear the Canvas:
var
w
=
theCanvas
.
width
;
var
h
=
theCanvas
.
height
;
context
.
clearRect
(
0
,
0
,
w
,
h
);
Let’s test out using the clearRect()
function by animating a path
across the Canvas (Example 2-28). We will
accomplish this by implementing the setTimeOut()
function presented in Chapter 1. It will be used to repeatedly
call our drawScreen()
function and
update the location of the path. The entire set of code for this example
is presented because it is more involved than simply drawing a path or a
shape on the Canvas at a single time.
Example 2-28. Using the clearRect() function
<!doctype html>
<html
lang=
"en"
>
<head>
<meta
charset=
"UTF-8"
>
<title>
Chapter 2 Example 28: Animating a Path</title>
<
script
src
=
"modernizr.js"
><
/script>
<
script
type
=
"text/javascript"
>
window
.
addEventListener
(
'load'
,
eventWindowLoaded
,
false
);
function
eventWindowLoaded
()
{
canvasApp
();
}
function
canvasSupport
()
{
return
Modernizr
.
canvas
;
}
function
canvasApp
(){
if
(
!
canvasSupport
())
{
return
;
}
else
{
var
theCanvas
=
document
.
getElementById
(
'canvas'
);
var
context
=
theCanvas
.
getContext
(
'2d'
);
}
var
yOffset
=
0
;
function
drawScreen
(){
context
.
clearRect
(
0
,
0
,
theCanvas
.
width
,
theCanvas
.
height
);
var
currentPath
=
context
.
beginPath
();
context
.
strokeStyle
=
"red"
;
//need list of available colors
context
.
lineWidth
=
5
;
context
.
moveTo
(
0
,
0
+
yOffset
);
context
.
lineTo
(
50
,
0
+
yOffset
);
context
.
lineTo
(
50
,
50
+
yOffset ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.