HTML and CSS Reference
In-Depth Information
Animating a Transformed Image
Toapplyaseriesofimagetilestotherotatedcontext,wesimplyhavetoaddbackintheframe
added this into the code for
Example 4-7
.
Example 4-8. Animation and rotation
var
var
tileSheet
=
new
new
Image
();
tileSheet
.
addEventListener
(
'load'
,
eventSheetLoaded
,
false
false
);
tileSheet
.
src
=
"tanks_sheet.png"
;
var
var
animationFrames
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
];
var
var
frameIndex
=
0
;
var
var
rotation
=
90
;
var
var
x
=
50
;
var
var
y
=
50
;
function
function
eventSheetLoaded
() {
startUp
();
}
function
function
drawScreen
() {
//draw a background so we can see the Canvas edges
context
.
fillStyle
=
"#aaaaaa"
;
context
.
fillRect
(
0
,
0
,
500
,
500
);
context
.
save
();
context
.
setTransform
(
1
,
0
,
0
,
1
,
0
,
0
)
var
var
angleInRadians
=
rotation
*
Math
.
PI
/
180
;
context
.
translate
(
x
+
16
,
y
+
16
)
context
.
rotate
(
angleInRadians
);
var
var
sourceX
=
Math
.
floor
(
animationFrames
[
frameIndex
]
%
8
)
*
32
;
var
var
sourceY
=
Math
.
floor
(
animationFrames
[
frameIndex
]
/
8
)
*
32
;
context
.
drawImage
(
tileSheet
,
sourceX
,
sourceY
,
32
,
32
,
-
16
,
-
16
,
32
,
32
);
context
.
restore
();
frameIndex
++
;
iif
(
frameIndex
==
animationFrames
.
length
) {
frameIndex
=
0
;
}
}