HTML and CSS Reference
In-Depth Information
Moving an Image
Moving an image on a cubic Bezier curve path is just as easy as moving a circular drawing
object,aswe'lldemonstrateinthenexttwoexamples.Supposeyouaremakingagamewhere
bull's-eyes move across the canvas and the player must shoot at them. You could use cubic
Bezier curve paths to create new and interesting patterns for the bull's-eyes to move along.
Forthisexample,wefirstcreateaglobalvariablenamed
bullseye
,whichwewillusetohold
the
bullseye.png
image that we will load to display on the canvas:
var
var
bullseye
;
function
function
eventWindowLoaded
() {
bullseye
=
new
new
Image
();
bullseye
.
src
=
"bullseye.png"
bullseye
.
onload
=
eventAssetsLoaded
;
}
In
canvasApp()
,wewillcreateadifferentpathforthecurvefromtheoneinthefirstexample
by setting new values for
p0
,
p1
,
p2
, and
p3
. Using these values, the
bullseye
will move on
a parabola-like path. (
Figure 5-16
shows the path of the curve.)
var
var
p0
=
{
x
:
60
,
y
:
10
};
var
var
p1
=
{
x
:
150
,
y
:
350
};
var
var
p2
=
{
x
:
300
,
y
:
375
};
var
var
p3
=
{
x
:
400
,
y
:
20
};
We also need to create a
player
object that represents the bull's-eye on the canvas:
var
var
player
=
{
x
:
0
,
y
:
0
,
speed
:
.
01
,
t
:
0
};
In
drawImage()
, after we calculate
t
,
xt
, and
yt
, we draw the image on the canvas:
player
.
x
=
xt
-
bullseye
.
width
/
2
;
player
.
y
=
yt
-
bullseye
.
height
/
2
;
context
.
drawImage
(
bullseye
,
player
.
x
,
player
.
y
);