Can canvas.getContext ("2d") return the same instance every time?

I would like to know if canvas.getContext("2d") guaranteed to return the same context instance every time it calls.

I want to know because I'm trying to follow the tips in this answer so that my scaled canvases don't look blurry. But I create a lot of canvases in my game, so I would like to createCanvas function that can be used by everyone. 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 each time, this will have no effect. I need to return the canvas because other code uses this.

Is there a better solution to this problem? If so, I agree with this and rename my title.


EDIT: After I asked, I noticed in this article , you can get the canvas out of context by running ctx.canvas . Pretty good advice.

+6
source share
1 answer

For any canvas element, canvas.getContext("2d") always returns the context of the same canvas element.

If you create a new canvas element with document.createElement("canvas") (or the equivalent of jquery), then getContext on this new canvas will return a unique context for this new canvas.

+8
source

Source: https://habr.com/ru/post/971474/


All Articles