We can revert back to previous style combinations.
The HTML5 canvas API can control the context state stack.
We can save and restore context states.
The following code shows how the state stack works by saving the context state.
<html> <head> <script> window.onload = function(){ let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); // draw rectangle context.beginPath(); /*from w w w. j a v a2s . c o m*/ context.rect(150, 30, 130, 130); context.fillStyle = "red"; context.fill(); // wrap circle drawing code with save-restore combination context.save(); context.globalAlpha = 0.2; // set global alpha context.beginPath(); context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 * Math.PI, false); context.fillStyle = "yellow"; context.fill(); context.restore(); // draw another rectangle context.beginPath(); context.rect(canvas.width - (150 + 130), canvas.height - (30 + 130), 130, 130); context.fillStyle = "blue"; context.fill(); }; </script> </head> <body> <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas> </body> </html>
In the code above we saved and restored the drawing states.