Use Translation to Anchor a Scaled Drawing
When scaling the trees in the previous challenge, the tops and bottoms of the
trees were no longer lined up even though all four trees were positioned at the
same y-coordinate. This is because the
context.scale()
method applies its scale factors to the coordinate system, not individual drawings.
When the coordinate system is scaled, every point in the coordinate system moves
either closer to or farther away from the origin, except the origin itself. Since
the origin doesn't move, it acts as a kind of anchor point.
In this example, we draw two trees. One tree is drawn while the origin of the
coordinate system is in the top left corner of the canvas. This is the origin's default
position. Before drawing the other tree, we move the origin to the base of the tree
using the
context.translate()
method. Because the origin of the coordinate system is positioned at the base of the
tree, the base of the tree does not move when the coordinate system is scaled.
We start by modifying the
drawTree()
function so the bottom center point of the tree is now drawn at the
x
and
y
values passed into the function.
function drawTree(x, y) {
context.fillStyle = 'Sienna';
context.fillRect(x - 10, y - 100, 20, 100);
context.fillStyle = 'ForestGreen';
context.beginPath();
context.arc(x, y - 100, 30, 0, 2 * Math.PI, false);
context.fill();
}
We position the first tree normally. The origin of the coordinate system
is in the top left corner of the canvas and the bottom center point of the
tree is positioned at (60, 150), which is the point 60 pixels to the right
of the origin and 150 pixels down.
context.save();
context.scale(1, 1); // Scale the coordinate system to draw the first tree
drawTree(60, 150); // Draw the first tree so its bottom center point is at (60, 150)
context.restore();
Try changing the scale of the coordinate system before the first tree is drawn.
Increasing the scale moves the tree farther from the origin. Decreasing the scale
moves it closer.
Instead of positioning the second tree by passing in
x
and
y
values, we use the
context.translate()
method to move the origin of the coordinate system to where we want to draw the tree.
By moving the origin, we can actually position the bottom center point of the tree at
the origin (0, 0).
context.save();
context.translate(320, 280); // Move the origin of the coordinate system to (320, 280)
context.scale(1, 1); // Scale the coordinate system to draw the second tree
drawTree(0, 0); // Draw the second tree so its bottom center point is at the origin (0, 0)
context.restore();
Try changing the scale of the coordinate system before the second tree is drawn.
Because the bottom center point of the tree is at the origin, the bottom center point
of the tree is anchored and does not move.
To learn more about translating the coordinate system, visit the
translate()
lesson.
Quick Reference:
Coordinates
Variables
Functions
fillRect()
fillStyle
save() / restore()
translate()