LoginSignup
7
4

More than 1 year has passed since last update.

canvasアニメーションを使ってみた

Last updated at Posted at 2022-08-07

canvas要素を使用したアニメーションを使用したことがなかったので、試してみました。
マウスをcanvas上に載せるとアニメーション開始、外すと停止する簡単なアニメーションです。

コードはこちら
CodePen

アニメーション

canvasとは

HTML5から追加され、HTML上に図形(ビットマップ画像)やグラフィックをJavaScriptによって描画できる技術です。
他にも、アニメーション、ゲームのグラフィック、データの可視化、写真加工、リアルタイム動画処理などに使用することができるそうです。
HTMLの要素とキャンバスAPIなどを使用して描画します。

コード

HTMLはcanvas要素、id属性、width属性、height属性を指定しています。
width、heightは描画範囲になりますが、指定しなければ初期値のwidth300px、height150pxが設定されます。

HTML
<canvas id="canvas" width="600" height="300"></canvas>

CSSは特に指定しなくても問題ないですが、
余白削除とcanvas要素の範囲をわかりやすくするために設定しています。

CSS
/* reset */
* {
  margin: 0;
  padding: 0;
}

#canvas {
  background: #eee;
}

JSはコメントアウトで説明を記述しています。

JS
const canvas = document.querySelector('#canvas');
// キャンパスに描画するためのCanvasRenderingContext2Dオブジェクトを取得するメソッド
// 二次元グラフィックを描画するために2dの指定
const ctx = canvas.getContext('2d');
let x = canvas.width / 2;
let y = canvas.height - 30;
let dx = 5;
let dy = 2;
let radius = 20;
let af;

//----- ボールの描画 -----//
function drawBall() {
  // 新しいパスを作成する際の先頭を指定
  ctx.beginPath();
  // arc(円弧の中心の水平座標, 円弧の中心の垂直座標, 円弧の半径, 円弧の開始角度(0°), 円弧の終了角度(360°))
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  // 色の指定
  ctx.fillStyle = "#0095DD";
  // 図形の塗りつぶし
  ctx.fill();
}

//----- ボールの挙動 -----//
function draw() {
  // 図形をクリアする際に使用。図形は切り抜かれて透明に
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall();
  x += dx;
  y += dy;

  // 衝突検知
  if (y + dy + radius > canvas.height || y + dy - radius < 0) {
    dy = -dy;
  }
  if (x + dx + radius > canvas.width || x + dx - radius < 0) {
    dx = -dx;
  }

  // 繰り返し処理開始
  // ディスプレイのリフレッシュ・レートによって更新速度が変化する
  af = requestAnimationFrame(draw);
}

canvas.addEventListener('mouseover', function (e) {
  // 繰り返し処理開始
  af = requestAnimationFrame(draw);
});

canvas.addEventListener('mouseout', function (e) {
  // 繰り返し処理の停止
  cancelAnimationFrame(af);
});

drawBall();

おまけ

上記の2Dアニメーションだとcanvasタグを使用しなくても実装できそうですが、今後3Dアニメーションを行う上でcanvasAPIの動作を知るにはちょうど良いのではないかと思いました。
簡単ですが、canvasAPIとライブラリを使用してテキストのアニメーションを試してみました。

コードはこちら
Codepen

最近は3Dアニメーションのためのライブラリが充実しており、リッチなWEBサイトが非常に多くなってきています。
そんなWEBサイトを作ってみたいですし、WEBグラフィックを作れたらかっこいいですよね。

参考サイト

https://vincentgarreau.com/particles.js/
https://balance.bz/magazine/webgr2022/
https://dribbble.com/tags/particle_js
https://developer.mozilla.org/ja/docs/Web/HTML/Element/canvas

7
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4