CoffeeScript Exchange Variable

I am new to CoffeeScript and trying to figure out how to refactor this example. Since both functions separate the canvas and the context, is there a way to get them out of the function and share them instead of repeating themselves? I am sure that this is something obvious that I am missing, but I could not get it to work.

CoffeeScript File

@draw_rectangle = -> canvas = document.getElementById("main_canvas") context = canvas.getContext("2d") context.fillRect(50, 25, 150, 100) @draw_square = -> canvas = document.getElementById("main_canvas") context = canvas.getContext("2d") context.fillRect(100, 50, 100, 50) 

HTML body:

 <body> <canvas id="main_canvas"></canvas> <p><a onclick="draw_square()" href="#">Draw Square</a></p> <p><a onclick="draw_rectangle()" href="#">Draw Rectangle</a></p> </body> 
+4
source share
2 answers

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.

+6
source

You can use your own helper method to draw a rectangle.

 canvasRectangle = (id, x, y, w, h) -> canvas = document.getElementById(id) context = canvas.getContext("2d") context.fillRect(x, y, w, h) @draw_rectangle = -> canvasRectangle("main_canvas", 50, 25, 150, 100) @draw_square = -> canvasRectangle("main_canvas", 100, 50, 100, 50) 
0
source

All Articles