-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcanvas.js
More file actions
80 lines (70 loc) · 1.9 KB
/
canvas.js
File metadata and controls
80 lines (70 loc) · 1.9 KB
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
80
export const makeCanvasManager = ({
initialWidth,
initialHeight,
maxWidth,
attachNode,
}) => {
let width = Math.min(initialWidth, maxWidth);
let height = initialHeight;
const element = document.createElement("canvas");
const context = element.getContext("2d", {
colorSpace: "display-p3",
});
const scale = window.devicePixelRatio;
const setCanvasSize = () => {
element.style.width = width + "px";
element.style.height = height + "px";
element.width = Math.floor(width * scale);
element.height = Math.floor(height * scale);
context.scale(scale, scale);
};
setCanvasSize();
document.querySelector(attachNode).appendChild(element);
window.addEventListener("resize", () => {
width = Math.min(window.innerWidth, maxWidth);
height = window.innerHeight;
setCanvasSize();
});
return {
getElement: () => element,
getContext: () => context,
getWidth: () => width,
getHeight: () => height,
getScaleFactor: () => scale,
};
};
export const makeOffscreenCanvas = ({
width,
height,
scale = window.devicePixelRatio,
}) => {
const offscreenElement = new OffscreenCanvas(width, height);
const context = offscreenElement.getContext("2d", {
colorSpace: "display-p3",
});
let _width = width;
let _height = height;
let _scale = scale;
const setCanvasSize = ({
width = _width,
height = _height,
scale = _scale,
} = {}) => {
_width = width;
_height = height;
_scale = scale;
offscreenElement.width = Math.floor(_width * _scale);
offscreenElement.height = Math.floor(_height * _scale);
context.scale(_scale, _scale);
};
setCanvasSize();
return {
getContext: () => context,
getBitmap: () => offscreenElement.transferToImageBitmap(),
getElement: () => offscreenElement,
getWidth: () => _width,
getHeight: () => _height,
getScaleFactor: () => _scale,
setCanvasSize,
};
};