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.
getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.
The getContext() function is the function that you use to get access to the canvas tags 2D drawing functions. As of April 2014, there are two types of context that are available to you: 2d and webgl . These provide you with the API that you use to draw on the canvas.
You cannot use multiple contexts for one canvas element. In WebKit, this is explicitly mentioned in the source: // A Canvas can either be "2D" or "webgl" but never both.
It is just name for variable. It could be anything. Ctx is just short word for ConTeXt.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With