Рисование и анимация

Анимации и продвинутое рисование на Canvas.

Зачем нужно

requestAnimationFrame — основа плавной анимации (60fps). Позволяет создавать игры, визуализации частиц, интерактивные графики без внешних библиотек.

Где используется

  • Игровые движки на Canvas
  • Анимированные фоны и эффекты
  • Визуализация данных в реальном времени

Code

const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');

// Анимационный цикл
let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = '#3498db';
  ctx.beginPath;
  ctx.arc(x, 150, 20, 0, Math.PI * 2);
  ctx.fill;

  x = (x + 2) % canvas.width;
  requestAnimationFrame(animate);
}
animate;

// Трансформации
ctx.save;
ctx.translate(100, 100);
ctx.rotate(Math.PI / 4);
ctx.scale(2, 2);
ctx.fillRect(-10, -10, 20, 20);
ctx.restore;

// Градиент
const grad = ctx.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, 'red');
grad.addColorStop(1, 'blue');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 200, 50);

// Тень
ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 10;
ctx.shadowOffsetX = 5;

// Интерактивность
canvas.addEventListener('click', (e) => {
  const rect = canvas.getBoundingClientRect();
  const mx = e.clientX - rect.left;
  const my = e.clientY - rect.top;
});

Связанные темы

Ресурсы