HTML and CSS Reference
In-Depth Information
We need to find the video's center on the canvas so 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 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. Since 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 up-
date 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 () {
//Background
context.fillStyle = '#ffffaa';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(5, 5, theCanvas.width−10, theCanvas.height−10);
//video
//*** Start rotation calculation
context.save();
context.setTransform(1,0,0,1,0,0);
var angleInRadians = rotation * Math.PI / 180;
var x = 100;
var y = 100;
var videoWidth=320;
var videoHeight=240;