HTML5 Game - Saving and Restoring Drawing States

Description

Saving and Restoring Drawing States

Demo

ResultView the demo in separate window

<!DOCTYPE html> 
<html> 
    <head> 
        <title>Canvas Demo</title> 
        <style> 
canvas { //from   w w w  .j  a  va 2s  . c  o  m
  border: 1px solid #000; 
} 
        </style> 
    </head> 
    <body> 
      <canvas id="myCanvas" width="200" height="210">Did You Know: Every time 
        you use a browser that doesn't support HTML5
      </canvas> 
      <script> 
// Get the context we will be using for drawing. 
let myCanvas = document.getElementById('myCanvas'); 
let myContext = myCanvas.getContext('2d'); 
  
// Create an array of colors to load into the stack. 
let allTheColors = ['#ff0000', '#ff8800', '#ffff00', '#00ff00', '#0000ff', 
    '#4b0082', '#8f00ff']; 
  
// Load the colors and stroke style into the stack. 
for (let i = 0; i < allTheColors.length; i++) { 
  myContext.strokeStyle = allTheColors[i]; 
  myContext.lineWidth = 30; 
  myContext.save(); 
} 
  
// Restore colors from the stack and draw. 
for (let i = 0; i < 8; i++) { 
  myContext.restore(); 
  myContext.beginPath(); 
  myContext.moveTo(0, ((30 * i) + 15)); 
  myContext.lineTo(200, ((30 * i) + 15)); 
  myContext.stroke(); 
} 
      </script> 
    </body> 
</html>

Related Topic