【发布时间】:2014-08-19 18:02:02
【问题描述】:
我想知道canvas.getContext("2d") 是否保证每次调用时都返回相同的上下文实例。
我想知道的原因是因为我正在尝试关注the advice in this answer,以便我的缩放画布看起来不会模糊。但是我在我的游戏中创建了许多画布,所以我想做一个所有人都可以使用的createCanvas 函数。我希望它看起来像这样:
function createCanvas(x, y) {
canvas = $("<canvas width='" + x + "' height='" + y + "'></canvas>")[0];
ctx = canvas.getContext("2d");
ctx.imageSmoothingEnabled = false; //modify the context
return canvas; //return the canvas, not the ctx
}
如果canvas.getContext("2d") 每次都返回一个新实例,这不会有任何影响。我需要返回画布,因为其他代码使用它。
这个问题有更好的解决方案吗?如果是这样,我会接受并重命名我的头衔。
编辑:在我询问后,我注意到this article 说您可以通过执行ctx.canvas 从上下文中获取画布。非常好的提示。
【问题讨论】:
-
请注意,您的代码中的
canvas返回一个 jquery 对象而不是 DOM 元素。为了提高性能,您不妨在本地创建 canvas 元素。
标签: javascript html canvas