]>
git.r.bdr.sh - rbdr/heart/blob - js/lib/heart_renderer.js
f6ece8630d57386ca19c165cdd67fe481d16c2ba
5 const kColorIteratorLimit
= 256;
7 const kGreenSpeed
= 0.2;
8 const kBlueSpeed
= 0.15;
11 * Renders a Heart, has its own canvas, which will be placed in the element
12 * set by calling #render.
14 * @class HeartRenderer
15 * @param {object} config configuration, extends any member of the renderer
17 const HeartRenderer
= class HeartRenderer
{
22 * The instance of the heart renderer being used
24 * @memberof HeartRenderer
27 * @type HTMLCanvasElement
28 * @default A brand new full width and height canvas
30 this.canvas
= window
.document
.createElement('canvas');
31 this.canvas
.style
.height
= '100%';
32 this.canvas
.style
.width
= '100%';
35 * The maximum fps that will be used
37 * @memberof HeartRenderer
45 this._animating
= false; // The status of the animation.
46 this._previousFrameTime
= Date
.now(); // The timestamp of the last frame for fps control
47 this._currentColor
= { // The current color that will be painted
53 Object
.assign(this, config
);
57 * Attaches the canvas to an HTML element
59 * @memberof HeartRenderer
62 * @param {HTMLElement} element the element where we will attach our canvas
66 element
.appendChild(this.canvas
);
70 * Gets the context from the current canvas and starts the animation process
72 * @memberof HeartRenderer
78 const context
= this.canvas
.getContext('2d');
79 this._startAnimating(context
);
83 * Stops the animation process
85 * @memberof HeartRenderer
86 * @function deactivate
91 this._stopAnimating();
94 // Starts the animation loop
95 _startAnimating(context
) {
97 this._frameDuration
= 1000 / this.fps
;
98 this._animating
= true;
100 this._animate(context
);
103 // Stops the animation on the next frame.
106 this._animating
= false;
109 // Runs the animation step controlling the FPS
112 if (!this._animating
) {
116 window
.requestAnimationFrame(this._animate
.bind(this, context
));
118 const currentFrameTime
= Date
.now();
119 const delta
= currentFrameTime
- this._previousFrameTime
;
121 if (delta
> this._frameDuration
) {
122 this._previousFrameTime
= Date
.now();
123 this._animateStep(context
, delta
);
127 // The actual animation processing function.
128 _animateStep(context
, delta
) {
130 this._currentColor
.red
= Math
.round(this._currentColor
.red
+ delta
* kRedSpeed
) % kColorIteratorLimit
;
131 this._currentColor
.green
= Math
.round(this._currentColor
.green
+ delta
* kGreenSpeed
) % kColorIteratorLimit
;
132 this._currentColor
.blue
= Math
.round(this._currentColor
.blue
+ delta
* kBlueSpeed
) % kColorIteratorLimit
;
134 context
.fillStyle
= `rgb(${this._currentColor.red}, ${this._currentColor.green}, ${this._currentColor.blue})`;
135 context
.fillRect(0, 0, this.canvas
.scrollWidth
, this.canvas
.scrollHeight
);
140 window
.HeartRenderer
= HeartRenderer
;