HTML and CSS Reference
In-Depth Information
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.translate() 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 con-
text, 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.
Here is the code for the final drawScreen() function for this example:
function drawScreen () {
context . fillStyle = '#ffffaa' ;
context . fillRect ( 0 , 0 , theCanvas . width , theCanvas . height );
Search WWH ::

Custom Search