Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Cached canvas drawing with coffee and extra sugar.

View example.coffee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# creating the cache object
context = document.getElementById('display').getContext '2d'
cache = new PaintCache context
 
# using the cache to speed up complex static drawing operations
cache.paintLayer 'background', (layer) =>
layer.beginPath()
layer.strokeStyle = 'red'
layer.lineWidth = 4
layer.moveTo 10, 10
layer.lineTo 10, 30
layer.lineTo 30, 30
layer.lineTo 40, 70
layer.quadraticCurveTo 72, 43, 22, 12
layer.quadraticCurveTo 12, 43, 12, 102
layer.stroke()
 
# invalidating a cached layer
cache.invalidateLayer 'background'
View example.coffee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
class PaintCache
constructor: (@context) ->
@layerCache = { }
paintLayer: (name, options, fn) ->
if arguments.length == 2
fn = options
options = { }
defaults =
x: 0
y: 0
width: @context.canvas.width
height: @context.canvas.height
options = defaults extends (options ? { })
if name of @layerCache
layer = @layerCache[name]
else
layerCanvas = document.createElement 'canvas'
layerCanvas.width = options.width
layerCanvas.height = options.height
@layerCache[name] = layer =
valid: false
canvas: layerCanvas
context: layerCanvas.getContext('2d')
unless layer.valid
layer.context.clearRect options.x, options.y, options.width, options.height
fn layer.context
@context.drawImage layer.canvas, options.x, options.y
layer.valid = true
invalidateLayer: (name) ->
@layerCache[name].valid = false if name of @layerCache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.