Probably the most elegant way would be to use a class, or at least an object that will contain both the methods and the canvas and context variables. The object will also track whether it has already been initialized. Here's the first attempt:
painter = draw_rectangle: -> @init() unless @initialized @context.fillRect 50, 25, 150, 100 draw_square: -> @init() unless @initialized @context.fillRect 100, 50, 100, 50 init: -> canvas = document.getElementById "main_canvas" @context = canvas.getContext "2d" @initialized = true
Now, if you later decided that you want to have several canvases, it would be very easy to change painter = to class Painter and reuse the code.
source share