39
context.setTransform(1,0,0,1,0,0);
Then we need to set up some variables that will be used for the rotation calculation. The
x and y variables set the upper-left location of the video on the canvas. The video
Width and videoHeight variables will be used to help rotate the video from the center:
var x = 100;
var y = 100;
var videoWidth=320;
var videoHeight=240;
Now it is time to use the rotation variable, which represents the angle that we rotated
the video on the canvas. It starts at 0, and we will increase it every time drawScreen()
is called. However, the context.rotate() method requires an angle to be converted to
radians when passed as its lone parameter. The following line of code converts the value
in the rotation variable to radians and stores it in a variable named angleInRadians:
var angleInRadians = rotation * Math.PI / 180;
We need to find the video’s center on the canvas so that we can start our rotation from
that point. We find the x value by taking our videoX variable and adding half the width
of the video. We find the y value by taking our videoY variable and adding half the height
of the video. We supply both of those values as parameters to the context.trans
late() function so that the rotation will begin at that point. We need to do this because
we are not rotating the video object—we are rotating the entire canvas in relation to the
displayed video:
context.translate(x+.5*videoWidth, y+.5*videoHeight);
The rest of the code is really straightforward. First, we call the rotate() function of the
context, passing our angle (converted to radians) to perform the rotation:
context.rotate(angleInRadians);
Then we call drawImage(), passing the video object and the x,y positions of where we
want the video to be displayed. This is a bit tricky but should make sense. Because we
used the context.translate() function to move to the center of the video, we now
need to place it in the upper-left corner. To find that corner, we need to subtract half
the width to find the x position and half the height to find the y position:
context.drawImage(videoElement ,-.5*videoWidth, -.5*videoHeight);
Finally, we restore the canvas we saved before the transformation started, and we update
the rotation variable so that we will have a new angle on the next call to drawScreen():
context.restore();
rotation++;
Now the video should rotate at 1 degree clockwise per call to drawScreen() while fading
onto the canvas. You can easily increase the speed of the rotation by changing the value
that you input for the rotation variable in the last line in the drawScreen() function.
336 | Chapter 6: Mixing HTML5 Video and Canvas