HTML and CSS Reference
In-Depth Information
ctx.save();
ctx.fillStyle = “blue";
ctx.fillRect(60,0,50,50);
ctx.restore();
// Back to red again.
ctx.fillRect(120,0,50,50);
In this example, you set the
fillStyle
to
red
and draw the first square. You then call the
save()
function,
which takes a snapshot of your current styles and saves them in memory. You then change the
fillStyle
to
blue
and draw another square. Then you call the
restore()
function, which retrieves your saved styles (setting
fillStyle
back to
red
). Just to prove that everything is working correctly, you draw another square that should
come out red. Figure 14-15 shows how this would look on the canvas.
Figure 14-15
Saving and restoring state.
You can use the
save()
and
restore()
functions to solve the text shadow problem. If you call the
save()
function before you set the shadow styles and then the
restore()
function before you draw the offer text, the text
will have no shadow.
The code in this exercise can be found in folder 11.
Here are the steps:
1.
Open the
adscript.js
file.
2.
Add a call to the
save()
function just before you set the shadow styles.
function drawAdvert() {
...
// Save the context
ctx.save();
// Set a shadow
...
}
3.
Now add a call to the
restore()
function before you draw the offer text.