JavaScriptで作るクリエイティブコーディング:Canvas APIを駆使したアート

JavaScriptで作るクリエイティブコーディング:Canvas APIを駆使したアート

Canvas APIは、2Dおよび3DグラフィックスをJavaScriptで描画するための強力なツールです。この記事では、Canvasを活用してインタラクティブでダイナミックなアート作品を作成する方法を解説します。

Canvas APIの基本

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

// 四角形を描画
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);

線を描画する

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.strokeStyle = 'red';
ctx.stroke();

円を描画する

ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();

グラデーションの適用

const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);

画像を描画する

const img = new Image();
img.src = 'path/to/image.jpg';
img.onload = () => {
  ctx.drawImage(img, 0, 0, 150, 100);
};

アニメーションを作る

let x = 0;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'purple';
  ctx.fillRect(x, 50, 50, 50);
  x += 2;

  if (x < canvas.width) {
    requestAnimationFrame(animate);
  }
}

animate();

インタラクティブアート

canvas.addEventListener('mousemove', (event) => {
  const x = event.offsetX;
  const y = event.offsetY;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'orange';
  ctx.beginPath();
  ctx.arc(x, y, 30, 0, Math.PI * 2);
  ctx.fill();
});

フラクタルアートを生成

function drawFractal(x, y, size) {
  if (size < 2) return;

  ctx.fillStyle = `rgb(${size * 5}, 0, ${255 - size * 5})`;
  ctx.fillRect(x, y, size, size);

  drawFractal(x - size / 2, y - size / 2, size / 2);
  drawFractal(x + size / 2, y - size / 2, size / 2);
  drawFractal(x - size / 2, y + size / 2, size / 2);
  drawFractal(x + size / 2, y + size / 2, size / 2);
}

drawFractal(200, 200, 128);

パーティクルシステムの作成

const particles = [];

function createParticle(x, y) {
  return { x, y, vx: Math.random() * 2 - 1, vy: Math.random() * 2 - 1 };
}

for (let i = 0; i < 100; i++) {
  particles.push(createParticle(canvas.width / 2, canvas.height / 2));
}

function updateParticles() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  particles.forEach(p => {
    p.x += p.vx;
    p.y += p.vy;

    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
    ctx.fill();
  });

  requestAnimationFrame(updateParticles);
}

updateParticles();

テキストを描画

ctx.font = '30px Arial';
ctx.fillStyle = 'yellow';
ctx.fillText('Hello Canvas', 50, 50);

複雑な形状の描画

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(150, 50);
ctx.lineTo(200, 100);
ctx.closePath();
ctx.fillStyle = 'pink';
ctx.fill();

音楽と同期するビジュアライザー

Audio APIを組み合わせたアート作品もCanvasで可能です。

// 音楽ビジュアライザーの例
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const analyser = audioContext.createAnalyser();
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
  const source = audioContext.createMediaStreamSource(stream);
  source.connect(analyser);

  function visualize() {
    const dataArray = new Uint8Array(analyser.frequencyBinCount);
    analyser.getByteFrequencyData(dataArray);

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    dataArray.forEach((value, index) => {
      ctx.fillStyle = `hsl(${index}, 100%, 50%)`;
      ctx.fillRect(index * 5, canvas.height - value, 4, value);
    });

    requestAnimationFrame(visualize);
  }

  visualize();
});

まとめ

Canvas APIは、クリエイティブコーディングにおける強力なツールセットです。基本的な図形から高度なアート作品まで、幅広い表現が可能です。