-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·79 lines (68 loc) · 2.07 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/** @module createCanvasContext */
const contextTypeList = [
"2d",
"webgl",
"experimental-webgl",
"webgl2",
"webgl2-compute",
"bitmaprenderer",
"gpupresent",
"webgpu",
];
/**
* Create a RenderingContext (2d, webgl, webgl2, bitmaprenderer, webgpu), optionally offscreen for possible use in a Worker.
*
* @alias module:createCanvasContext
* @param {import("./types.js").ContextType} [contextType="2d"]
* @param {import("./types.js").CanvasContextOptions} [options={}]
* @returns {import("./types.js").CanvasContextReturnValue}
*/
function createCanvasContext(contextType = "2d", options = {}) {
// Get options and set defaults
const {
width,
height,
offscreen = false,
worker = false,
contextAttributes = {},
} = {
...options,
};
// Check contextType is valid
if (!worker && !contextTypeList.includes(contextType)) {
throw new TypeError(`Unknown contextType: "${contextType}"`);
}
// Return in Node or in a Worker unless a canvas is provided
// See https://github.com/Automattic/node-canvas for an example
if (typeof window === "undefined" && !options.canvas) {
return null;
}
// Get offscreen canvas if requested and available
const canvasEl = options.canvas || document.createElement("canvas");
const canvas =
(offscreen || worker) && "OffscreenCanvas" in window
? canvasEl.transferControlToOffscreen()
: canvasEl;
// Set canvas dimensions (default to 300 in browsers)
if (Number.isInteger(width) && width >= 0) canvas.width = width;
if (Number.isInteger(height) && height >= 0) canvas.height = height;
if (worker) return { canvas };
// Get the context with specified attributes and handle experimental-webgl
let context;
try {
context =
canvas.getContext(contextType, contextAttributes) ||
(contextType === "webgl"
? canvas.getContext("experimental-webgl", contextAttributes)
: null);
} catch (error) {
console.error(error);
context = null;
}
return {
canvas,
context,
};
}
export default createCanvasContext;
export * from "./types.js";