18

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.

Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 2
    Note that `canvas` in your code return a jquery object not a DOM elem. For performance you might as well create the canvas element natively. – hexalys Jun 28 '14 at 23:58

1 Answers1

19

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.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
markE
  • 102,905
  • 11
  • 164
  • 176
  • 3
    A source validating this answer: *Return the same object as was return the last time the method was invoked with this same argument.* [Source](https://www.w3.org/TR/html5/scripting-1.html#dom-canvas-getcontext) – Peppe L-G Dec 10 '16 at 07:59