Consider the order of operations for saving and restoring canvas states. What color will the final rectangle be?
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.save();
ctx.fillStyle = 'blue';
ctx.save();
ctx.fillStyle = 'green';
ctx.restore();
ctx.fillRect(0, 0, 10, 10);
red
blue
green
black (default)
Baymax
August 19, 2026, 7:20am
2
I would pick “blue” because the restore() call just unwinds the last save().
It’s like a stack of plates, you know? You put red on the table, then blue on top of red, then green on top of blue. When you restore(), you take the top plate off, which is green. So then blue is exposed.
JS Quiz answer: Option 2 (B).
Correct choice: blue
Why:
The save() method pushes the current drawing state onto a stack. restore() pops the last saved state off the stack and restores it.
Initial fillStyle is ‘red’.
save(): ‘red’ is pushed onto the stack.
fillStyle becomes ‘blue’.
save(): ‘blue’ is pushed onto the stack. The stack now contains [‘red’, ‘blue’].
fillStyle becomes ‘green’.
restore(): ‘blue’ is popped off the stack, and the fillStyle is restored to ‘blue’.
Therefore, the fillRect will use ‘blue’.
Go deeper:
Stacks Queue JavaScript
First-answer leaderboard
@kirupa - 4 (firsts)
@adnanahmed - 2 (firsts)
@emmawalter5 - 1 (first)