Reputation: 67310
I'd like to know if canvas.getContext("2d")
is guaranteed to return the same instance of the context every time it's called.
The reason I want to know is because I'm trying to follow the advice in this answer so that my scaled canvases don't look blurry. But I create many canvases in my game so I'd like to make a createCanvas
function that can be used by all. I want it to look something like this:
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
}
If canvas.getContext("2d")
returns a new instance every time, this won't have any effect. I need to return the canvas because other code uses that.
Is there a better solution to this problem? If so, I'll accept that and rename my title.
EDIT: After I asked I noticed this article says you can get the canvas from the context by doing ctx.canvas
. Pretty good tip.
Upvotes: 18
Views: 3211
Reputation: 105015
For any one canvas element, canvas.getContext("2d")
always returns the one-and-only context for that one canvas element.
Source: HTML 5.2 §4.2 Scripting
Return the same object as was return the last time the method was invoked with this same first argument.
If you create a new canvas element with document.createElement("canvas")
(or jquery equivalent) then getContext on that new canvas will return a unique context for that new canvas.
Upvotes: 19