CoffeeScript 重构共享变量
我是 CoffeeScript 的新手,并试图了解如何重构这个示例。由于这两个函数共享画布和上下文,有没有办法将它们从函数中拉出并共享它们,而不是重复自己?我确信这是我明显遗漏的东西,但我无法让它发挥作用。
CoffeeScript 文件
@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>
<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>
I'm new to CoffeeScript and trying to understand how to refactor this example. Since both functions share canvas and context is there a way to pull them out side the functions and share them instead of repeating myself? I'm sure it is something obvious I'm missing, but I have not been able to 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用自定义辅助方法来绘制矩形。
You can use a custom helper method to draw a rectangle.
也许最优雅的方法是使用一个类,或者至少是一个对象,它可以保存方法以及canvas和context变量。该对象还将跟踪它是否已经被初始化。这是第一次尝试:
现在,如果您后来决定想要拥有多个画布,则可以很容易地将
painter =
更改为class Painter
并重用代码。Probably the most elegant way would be to use a class, or at least an object, that would hold both methods and the
canvas
andcontext
variables. The object would also keep track of whether it's been initialized already. Here's a first attempt:Now, if you later decided that you wanted to have multiple canvases, it'd be very easy to change
painter =
toclass Painter
and reuse the code.