Lazy Canvas Context

Source code on GitHub

On this web page the scripts

<script src=""></script>
<script src="LazyCanvasCtx.js"></script>
var ctx = new LazyCanvasCtx('canvas');
have been run. Open the JavaScript console to play with this ctx object, which behaves mostly like a normal canvas 2d context object.

For example, try

ctx.fillRect(0, 0, 100, 200);

This should immediately draw a black rectangle.

But once you set ctx.lazy = true further draw operations will be saved instead of running right away:

ctx.lazy = true;
ctx.fillRect(50, 50, 200, 10); // nothing happens!
You can run run these queued drawing operations by calling the trigger method:
ctx.trigger() // all the queued drawing operations occur
Some interactions, like reading a data property on the context, will force execution of pending operations in order to ensure an up-to-date value is returned.
ctx.lazy = true;
ctx.fillRect(50, 50, 200, 10); // nothing happens
console.log(ctx.strokeStyle);  // implicit .trigger() call, queued operations are run


This might be useful for batching draw operations that logically go together, but could be interrupted by DOM renders that would show the intermediate state.