HTML and CSS Reference
In-Depth Information
For our purposes, the
t
value will be increased by the
speed
at which we want the object to
move. However, you will notice that this value does not easily equate to the
speed
values we
used elsewhere in this chapter. The reason is that the
t
value was not created with movement
over time for animation in mind. The speed we specify must be smaller than
1
so that the
movement on the curve will be incremental enough for us to see it as part of the animation.
For our example, we will increase
t
by a speed of
.01
so that we will see
100
points on the
movement curve (1/100 = .01). This is advantageous because we will know our object has
finished moving when the
t
value is equal to
1
.
For
Example 5-11
(
CH5EX11.html
), we will start by creating the four points of the Bezier
curve in the
canvasApp()
function:
var
var
p0
=
{
x
:
60
,
y
:
10
};
var
var
p1
=
{
x
:
70
,
y
:
200
};
var
var
p2
=
{
x
:
125
,
y
:
295
};
var
var
p3
=
{
x
:
350
,
y
:
350
};
We then create a new
ball
object with a couple differing properties from those in the other
examples in this chapter. The
speed
is
.01
, which means that the object will move 100 points
along the curve before it is finished. We start the
t
value at
0
, which means that the
ball
will
begin at
p0
:
var
var
ball
=
{
x
:
0
,
y
:
0
,
speed
:
.
01
,
t
:
0
};
Next, in the
drawScreen()
function, we calculate the Bezier curve coefficient values (
ax
,
bx
,
cx
,
ay
,
by
,
cy
) based on the four points (
p0
,
p1
,
p2
,
p3
):
var
var
cx
=
3
*
(
p1
.
x
-
p0
.
x
);
var
var
bx
=
3
*
(
p2
.
x
-
p1
.
x
)
-
cx
;
var
var
ax
=
p3
.
x
-
p0
.
x
-
cx
-
bx
;
var
var
cy
=
3
*
(
p1
.
y
-
p0
.
y
);
var
var
by
=
3
*
(
p2
.
y
-
p1
.
y
)
-
cy
;
var
var
ay
=
p3
.
y
-
p0
.
y
-
cy
-
by
;
Thenwetakeour
t
valueanduseitwiththecoefficientstocalculatethe
x
and
y
valuesforthe
moving object. First, we get the
t
value from the
ball
object, and we store it locally so that
we can use it in our calculations:
var
var
t
=
ball
.
t
;
Next we add the
speed
to the
t
value so that we can calculate the next point on the Bezier
path: