HTML and CSS Reference
In-Depth Information
Next,weneedtofindtheangleinradiansforthedirectionthatwewantthetanktoberotated.
For this example, we will choose 90 degrees:
var
var rotation = 90 ;
var
var angleInRadians = rotation * Math . PI / 180 ;
context . rotate ( angleInRadians );
Step 4: Draw the image
When we draw the image, we must remember that the drawing's point of origin is no longer
the 50,50 point from previous examples. After the transformation matrix has been applied to
translate to a new point, that point is now considered the 0,0 origin point for drawing.
This can be confusing at first, but it becomes clear with practice. To draw our image with
50,50 as the top-left coordinate, we must subtract 16 from the current position in both the x
and y directions:
context . drawImage ( tileSheet , sourceX , sourceY , 32 , 32 , - 16 , - 16 , 32 , 32 );
Example 4-7 adds in this rotation code to Example 4-4 . When you run the example now, you
will see the tank facing to the right.
Example 4-7. Rotation transformation
var
var tileSheet = new
new Image ();
tileSheet . addEventListener ( 'load' , eventSheetLoaded , false
false );
tileSheet . src = "tanks_sheet.png" ;
var
var animationFrames = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ];
var
var frameIndex = 0 ;
var
var rotation = 90 ;
var
var x = 50 ;
var
var y = 50 ;
function
function eventSheetLoaded () {
drawScreen ();
}
function
function drawScreen () {
//draw a background so we can see the Canvas edges
context . fillStyle = "#aaaaaa" ;
context . fillRect ( 0 , 0 , 500 , 500 );
context . save ();
Search WWH ::




Custom Search