Based on how this method is used, it seems that a rendering context is kind of a “setting” of an html canvas element. You can set it to “2d”, “webgl”, “webgl2”, or “webgpu”
For other methods in JavaScript like getElementById(), getElementsByClassName(), it “gets” some element that already exist from the html document.
In the case of the getContext() method, it does not get a Rendering Context that already exists somewhere, but kind of creates a new Rendering Context or chooses a Rendering Context setting option for the selected canvas element. So why is this method named HTMLCanvasElement.getContext() instead of HTMLCanvasElement.setContext()? Wouldn’t it make more sense to name it HTMLCanvasElement.setContext()?
Besides, in the “The rendering context” in the Canvas API document page, it says: “The element creates a fixed-size drawing surface that exposes one or more rendering contexts...”
However, on the HTMLCanvasElement: getContext() method page, it says: “It is not possible to get a different drawing context object on a given canvas element.”
Are’t these 2 statement contradictory? I’m very confused.
getContext() is indeed a getter - it only creates a context if none exists. The "one or more" part refers to the fact that exactly one of each contextType may exist. If you remove the contextType argument, a basic singleton getter goes something like this:
class Singleton {
static _instance;
static getInstance() {
if (!this._instance)
this._instance = new this();
return this._instance;
}
}
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();
console.log(singleton1 === singleton2); // true