April 2, 2022

Thoughts Cloud


Have you been stressed lately?
Too many thoughts?
Just send them away to the clouds!

Project

https://ilya122.github.io/ThoughtsCloud/

Source code

This project is open source!

https://github.com/Ilya122/ThoughtsCloud

Some technicals

The whole app code is 157 lines of javascript code.

Canvas

A canvas is a drawing surface we can render text, shapes, images, etc…

To get the area of drawing we need 2 parameters:

1
2
3
<div id="main" class="container is-widescreen is-fluid" style="width:auto;height:640px">
<canvas id="drawingArea" style="width:100%;height:640px"></canvas>
</div>
1
2
canvas = document.getElementById('drawingArea');
ctx = canvas.getContext('2d');

Classes ES6

I like being OOP and I’m used to develop games in a predefined game loop.
A game loop is just a loop that does:

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
class Word {
constructor(text, x, y, velocityY, size, alpha = 1.0) {
this.Text = text;
this.X = x;
this.Y = y;
this.VelocityY = velocityY;
this.Size = size;
this.Alpha = alpha;
}

Update() {
this.VelocityY -= 1;
this.Y -= this.VelocityY;
this.Alpha -= 0.02;
}

Draw(context) {
context.fillStyle = "rgba(183, 234, 255, " + this.Alpha + ")";
context.font = `${this.Size}pt Arial`;
context.fillText(this.Text, this.X, this.Y);
}

IsStopped() {
return this.Alpha < 0;
}
}

class Cloud {
constructor(image, x, y, velocityX, velocityY) {
this.Image = image;
this.X = x;
this.Y = y;
this.VelocityX = velocityX;
this.VelocityY = velocityY;
}

Update(canvas) {
this.X += this.VelocityX;
this.Y += this.VelocityY;

if (this.X > canvas.width) {
this.X = 0;
}
}

Draw(context) {
context.drawImage(this.Image, this.X, this.Y);
}

}

The update causes X and Y positions to be updated.
The movement of the words are controlled by a Velocity variable.
By decreasing Velocity we create a “Ease out” effect.

The main drawing loop:

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
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);

for (let i = 0; i < window.clouds.length; i++) {
let cloud = window.clouds[i];
cloud.Update(canvas);
cloud.Draw(ctx);
}

ctx.font = '12px serif';

let len = window.wordList.length;
let toRemove = [];

for (let i = 0; i < len; i++) {
let word = window.wordList[i];
word.Update();
word.Draw(ctx);

if (word.IsStopped()) {
toRemove.push(word);
}
}

toRemove.forEach(word => {
const index = window.wordList.indexOf(word);
if (index > -1) {
window.wordList.splice(index, 1); // 2nd parameter means remove one item only
}
});
}

You can checkout the code in the repository.

Thank you for reading!

על הפוסט

הפוסט נכתב על ידי Ilya, רישיון על ידי CC BY-NC-ND 4.0.

שתפו את הפוסט

Email Facebook Linkedin Print

קנו לי קפה

#Programming#Projects