title: How to delete the state stack for a JavaScript canvas rendering context?
body: <p>I was recently working with <code>&lt;canvas&gt;</code> in JavaScript, and discovered the possibility to create a really bad "memory leak" (more like a memory explosion). When working with the canvas context, you have the ability to do <code>context.save()</code> to add the drawing styles to the "state stack" and <code>context.restore()</code> to remove it. (See <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D" rel="nofollow">the documentation for the rendering context on MDN</a>.)</p>
  
  <p>The problem occurs when you happen to continually save to the state stack without restoring. In Chrome v50 and Firefox v45 this seems to just take up more and more private memory, eventually crashing the browser tab. (Incidentally the JavaScript memory is unaffected in Chrome, so it's very hard to debug this with the profiler/timeline tools.)</p>
  
  <p>My question: <strong>How can you clear out or delete the state stack for a canvas context?</strong> With a normal array, you would be able to check on the <code>length</code>, trim it with <code>splice</code> or simply reset is back to empty <code>[]</code>, but I haven't seen a way to do any of this with the state stack.</p>