2 min. read


הייתם בהרבה לחץ לאחרונה?
יותר מדי מחשבות?
תשלחו אותם לעננים!

פרוייקט

קוד

כל הקוד זמין.

https://github.com/Ilya122/ThoughtsCloud

קצת נקודות טכניות

כל הקוד הוא 157 שורות של javascript.

Canvas

הקנבס הוא אזור לציור טקסט, צורות, תמונות וכדו’…

כדי לקבל את אזור הציור אנחנו צריכים 2 דברים:

  • קנבס - לציור
  • קונטקסט - מצייר למסך
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');

מחלקות

אני אוהב להשתמש ב-OOP ואני רגיל מפיתוח משחקים לצייר את זה בלולאת משחק.
לולאת משחק היא לולאה שעושה:

  • עדכון - מעדכנת את כל היישויות במסך
  • ציור - מצייר את המצב הנוכחי, בדרך כלל מנקה הכל ומצייר הכל מחדש
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);
}

}

התזוזה נעשת בעזרת עדכון הקורדינטות.
והיא נשלטת בידי משתנה Velocity.
כדי ליצור אפקט תזוזה שנחלש הקוד מוריד את הערך של Velocity.

לולאת הציור הראשית:

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
}
});
}

אתם יכולים לקרוא את הקוד בעצמכם.

תודה על הקריאה!


אהבתם? מוזמנים להביע תמיכה כאן: כוס קפה