HTML and CSS Reference
In-Depth Information
Scale Transformations
The context.scale() function takes in two parameters: the first is the scale attribute for the
x-axis, and the second is the scale attribute for the y-axis. The value 1 is the normal scale for
an object. Therefore, if we want to double an object's size, we can set both values to 2 . Using
the following code in drawScreen() produces the red square shown in Figure 2-18 :
context . setTransform ( 1 , 0 , 0 , 1 , 0 , 0 );
context . scale ( 2 , 2 );
context . fillStyle = "red" ;
context . fillRect ( 100 , 100 , 50 , 50 );
Figure 2-18. A simple scaled square
If you test this code, you will find that scale works in a similar manner as rotation. We did not
translate the origin of the scale point to double the size of the square; rather, we used the top-
left corner of the canvas as the origin point. The result is that the red square appears to move
fartherdownandtotheleft.Whatwewouldlikeisfortheredsquaretoremaininplaceandto
scale from its center. We do this by translating to the center of the square before we scale, and
by drawing the square around this center point (just as we did in Example 2-9 ) . Example 2-11
produces the result shown in Figure 2-19 .
Example 2-11. Scale from the center point
function
function drawScreen () {
//now draw a red square
context . setTransform ( 1 , 0 , 0 , 1 , 0 , 0 );
var
var x = 100 ;
var
var y = 100 ;
var
var width = 50 ;
var
var height = 50 ;
context . translate ( x + . 5 * width , y + . 5 * height );
context . scale ( 2 , 2 );
context . fillStyle = "red" ;
context . fillRect ( - . 5 * width , - . 5 * height , width , height );
Search WWH ::

Custom Search