Как создать эффект частиц на Canvas?

Пользователь

от rebekah , в категории: Другие , год назад

Как создать эффект частиц на Canvas?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

2 ответа

Пользователь

от camren , год назад

@rebekah 

Пользователь

от brook , месяц назад

@rebekah 

Для создания эффекта частиц на Canvas вам потребуется использовать JavaScript и HTML.


Вот пример кода, который создает эффект частиц на Canvas:


HTML:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Particle Effect</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>


JavaScript (script.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
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const particles = [];

class Particle {
  constructor(x, y, radius, color) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
    this.velocity = {
      x: Math.random() * 2 - 1,
      y: Math.random() * 2 - 1
    };
  }

  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
  }

  update() {
    this.draw();
    this.x += this.velocity.x;
    this.y += this.velocity.y;
    if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
      this.velocity.x = -this.velocity.x;
    }
    if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
      this.velocity.y = -this.velocity.y;
    }
  }
}

function init() {
  for (let i = 0; i < 100; i++) {
    const radius = Math.random() * 3 + 1;
    particles.push(new Particle(canvas.width / 2, canvas.height / 2, radius, 'blue'));
  }
}

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  particles.forEach(particle => {
    particle.update();
  });
}

init();
animate();


Запустив данный код, вы увидите эффект частиц на Canvas, где частицы случайно двигаются по экрану и отражаются от границ холста. Можете вносить изменения в параметры частиц (цвет, скорость, размер и другие параметры) и настраивать эффект по вашему усмотрению.