-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
125 lines (105 loc) · 2.61 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
'use strict';
var Renderable = require('./Renderable');
/**
* The Canvas constructor, which expects an HTML element referring to a canvas.
*
* @param {HTMLCanvasElement} element
*/
function Canvas(element) {
// Test if the provided element actually is a canvas.
var elementIsCanvas = !!(element.getContext && element.getContext('2d'));
if(!elementIsCanvas) {
throw new TypeError('The provided element is not a canvas element.');
}
// Store the reference to the DOM-element and
// the canvas 2d context.
this.el = element;
this.cx = this.el.getContext('2d');
// Keep a list of renderable items.
this.L = 0; // listeners number.
this.rs = [];
}
Canvas.prototype = {
/**
* Adds a renderable onto canvas.
*
* @param {Renderable} r renderable object.
*/
add: function(r) {
if (typeof r !== 'object' || !(r instanceof Renderable))
throw new TypeError('Invalid renderable provided');
this.rs.push(r);
this.L = this.rs.length;
},
/**
* Adds a renderable onto canvas (at the first list).
*
* @param {Renderable} r renderable object.
*/
prepend: function(r) {
if (typeof r !== 'object' || !(r instanceof Renderable))
throw new TypeError('Invalid renderable provided');
this.rs.unshift(r);
this.L = this.rs.length;
},
/**
* Remove a renderable.
*
* @param {Renderable} r renderable object.
*/
remove: function(r) {
this.rs.splice(r, 1);
this.L = this.rs.length;
},
/**
* Clear the canvas.
*/
clear: function() {
this.cx.clearRect(0, 0, this.el.width, this.el.height);
},
/**
* Get the canvas context.
*/
context: function() {
return this.cx;
},
/**
* Render all the renderables,
* like they want to be rendered!
*/
render: function() {
this.clear();
var ctx = this.cx;
var width = this.cx.canvas.width;
var height = this.cx.canvas.height;
for (var i = 0; i < this.L; i++) {
this.rs[i].render(ctx, width, height);
}
},
/**
* Resize the canvas.
*
* @param {number} w the width.
* @param {number} h the height.
*/
resize: function(w, h) {
// Get the device pixel ratio,
// falling back to 1.
var dpr = window.devicePixelRatio || 1;
// Give the canvas pixel dimensions * device pixel ratio.
this.cx.canvas.width = w * dpr;
this.cx.canvas.height = h * dpr;
// Scale all drawing operations by the dpr.
this.cx.scale(dpr, dpr);
},
/**
* Get the canvas size.
*/
size: function() {
return {
width: this.cx.canvas.width,
height: this.cx.canvas.height
};
},
};
module.exports = Canvas;