Как нарисовать анимированное море на Canvas?

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

от lilla.herman , в категории: Другие , 10 месяцев назад

Как нарисовать анимированное море на Canvas?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

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

от maya , 10 месяцев назад

@lilla.herman 

Для того, чтобы нарисовать анимированное море на Canvas, нужно выполнить следующие шаги:

  1. Создать Canvas элемент на странице HTML.
1
<canvas id="canvas"></canvas>


  1. Получить контекст 2D для Canvas.
1
2
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");


  1. Создать функцию для рисования воды и взрывов воды.
1
2
3
4
5
6
7
8
function drawWater() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.fillStyle = "blue";
  context.fillRect(0, 0, canvas.width, canvas.height);
  for(let i = 0; i < waterDroplets.length; i++) {
    waterDroplets[i].draw();
  }
}


  1. Создать класс для рисования отдельных капель воды.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class WaterDroplet {
  constructor(x, y, radius, speed) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.speed = speed;
  }
  draw() {
    context.beginPath();
    context.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    context.lineWidth = 2;
    context.fillStyle = "#4EA5D9";
    context.fill();
    context.strokeStyle = "#fff";
    context.stroke();
    this.update();
  }
  update() {
    this.y -= this.speed;
    if(this.y < -10) {
      this.y = canvas.height + 10;
    }
  }
}


  1. Создать массив для хранения всех капель воды и добавить новые водяные капли каждые несколько секунд.
1
2
3
4
5
6
7
8
let waterDroplets = [];
setInterval(() => {
  const x = Math.random() * canvas.width;
  const y = canvas.height + 10;
  const radius = Math.random() * 5 + 2;
  const speed = Math.random() * 3 + 1;
  waterDroplets.push(new WaterDroplet(x, y, radius, speed));
}, 300);


  1. Создать функцию анимации, которая будет отображать изменения в Canvas элементе.
1
2
3
4
5
function animate() {
  requestAnimationFrame(animate);
  drawWater();
}
animate();


Таким образом, простой пример анимированного моря на Canvas был создан!