Use restore() to go back to previous drawing context
<!doctype html> <html lang="en"> <body> <div style="position: absolute; top: 50px; left: 50px;"> <canvas id="canvas" width="500" height="500"> Your browser does not support the HTML 5 Canvas. </canvas>/*ww w .j ava 2s. c o m*/ <script type="text/javascript"> let theCanvas = document.getElementById('canvas'); let context = theCanvas.getContext('2d'); context.fillStyle = "#ff0000"; context.save(); context.fillStyle = "#00ff00"; context.translate(100, 100); context.save(); context.fillStyle = "#0000ff"; context.fillRect(0, 0, 100, 200); // draws blue rectangle at (100, 100) context.restore(); context.fillRect(10, 10, 100, 200); // draws green rectangle at (110, 110) context.restore(); context.fillRect(0, 0, 100, 200); // draws red rectangle at (0, 0) </script> </div> </body> </html>