如何使用 HTML5 Canvas 功能风格
我正在使用 HTML5 的 Canvas 元素进行一些工作,我想知道如何以功能性方式最好地实现我自己的自定义绘制函数。其中每个都需要上下文,但我可以想到多种方法来将其提供给它们:
- 将其作为参数添加到每个绘制函数调用
- 将其添加为全局变量
- 在每个绘制方法中调用“getContext”。
- 扩展“CanvasRenderingContext2D”的原型。
如果可以避免的话,我不喜欢使用全局变量,所以我正在逐步淘汰选项 2。选项 3 需要太多的代码重复,所以我也忽略它。
这给我留下了选择 1,这是我用非函数式语言实现的方法,而 4 在我看来是最干净的方法,但我不完全确定它不会导致问题。你怎么做?我有理由不选择选项 4 吗?
为了说明这一点,我将为每个剩余选项添加一个代码示例。这是选项 1:
function drawPerson(context, ...) {
context.fillRect(...);
...
}
$(function() {
var context = $("#canvas")[0].getContext("2d");
drawPerson(context, ...);
});
这里是选项 4:
CanvasRenderingContext2D.prototype.drawPerson = function(...) {
this.fillRect(...);
...
}
$(function() {
var context = $("#canvas")[0].getContext("2d");
context.drawPerson(...);
});
I'm doing some work with HTML5's Canvas element, and I'm wondering how to best implement my own, custom draw functions in a functional way. Each of these will need the context, but I can think of multiple ways to give it to them:
- Add it as a parameter to each draw function call
- Add it as a global variable
- Call "getContext" in each draw method.
- Extend the prototype of ´CanvasRenderingContext2D´.
I don't like to use global variables if I can avoid it, so I'm phasing out option 2. Option 3 requires way too much code duplication, so I also ignore that.
This leaves me with choice 1, which is how I would do it in a non-functional language and 4 which is in my opinion the cleanest approach, but I'm not entirely sure it won't lead to problems. How do you do it? Is there a reason why I shouldn't go with option 4?
To illustrate this, I'll add a code example for each of the remaining option. Here's option 1:
function drawPerson(context, ...) {
context.fillRect(...);
...
}
$(function() {
var context = $("#canvas")[0].getContext("2d");
drawPerson(context, ...);
});
And here option 4:
CanvasRenderingContext2D.prototype.drawPerson = function(...) {
this.fillRect(...);
...
}
$(function() {
var context = $("#canvas")[0].getContext("2d");
context.drawPerson(...);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
另一种选择是使用包含所有绘图函数和initialize()的模块:
这样只有一个全局变量,上下文仅设置一次,并且不会与其他对象混淆。
Another option is to use a module which contains all drawing functions and initialize():
That way there is only one global var, context is set only once and you don't mess with other objects.