forked from pencil-js/pencil.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffscreen-canvas.js
93 lines (84 loc) · 2.03 KB
/
offscreen-canvas.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Off-screen canvas class
* @class
*/
export default class OffScreenCanvas {
/**
* Off-screen canvas constructor
* @param {Number} [width=1] - Width of the canvas
* @param {Number} [height=1] - Height of the canvas
*/
constructor (width = 1, height = 1) {
this.ctx = window.document.createElement("canvas").getContext("2d");
this.width = width;
this.height = height;
}
/**
* @return {Number}
*/
get width () {
return this.ctx.canvas.width;
}
/**
* @param {Number} width - New width value
*/
set width (width) {
this.ctx.canvas.width = +width;
}
/**
* @return {Number}
*/
get height () {
return this.ctx.canvas.height;
}
/**
* @param {Number} height - New height value
*/
set height (height) {
this.ctx.canvas.height = +height;
}
/**
* Render a container and its children into the canvas
* @param {Container} container - Any container
* @return {OffScreenCanvas} Itself
*/
render (container) {
this.clear();
container.render(this.ctx);
return this;
}
/**
* Erase the canvas
* @return {OffScreenCanvas} Itself
*/
clear () {
this.ctx.clearRect(0, 0, this.width, this.height);
return this;
}
/**
* Put data into the canvas
* @param {ImageData} imageData - Data to add to the canvas
*/
set imageData (imageData) {
this.ctx.putImageData(imageData, 0, 0);
}
/**
* Return the whole canvas as data
* @return {ImageData}
*/
get imageData () {
return this.ctx.getImageData(0, 0, this.width, this.height);
}
/**
*
* @param {String} type -
* @return {HTMLImageElement}
*/
toImage (type = "image/png") {
const img = window.document.createElement("img");
img.width = this.width;
img.height = this.height;
img.src = this.ctx.canvas.toDataURL(type);
return img;
}
}