🖼️

canvasでアニメーション【文字を動かす】

2023/02/25に公開約1,900字

canvasとは

Webページ上に、動的なグラフィックスや図形、アニメーションを描画するためのHTMLタグ。
JavaScriptを使用してcanvas要素の中にグラフィックスやアニメーションを表示する。

まずは文字を描画してみる

index.html
<canvas id="myCanvas" width="200" height="100"></canvas>

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.font = "30px Arial";
  ctx.fillText("Hello World!", 10, 50);
</script>

アニメーションを作ってみる

アニメーションは「画面のクリア・図形の位置を動かす・描画」の処理を、繰り返し行うことで、パラパラ漫画のように見せて実現している。

例えば、ボールが落下するアニメーションは以下のようなコードになる。

index.html
<style>
    canvas {
        background-color: pink;
    }
</style>
<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var x = 100;
    var y = 0;
    var vy = 5;
    setInterval(function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath();
        ctx.arc(x, y, 10, 0, 2 * Math.PI);
        ctx.fill();
        y += vy;
    }, 50);
</script>

これらを応用して、

昔のホームページにあったような動く文字を作る

index.html
<style>
    canvas {
        background-color: black;
    }
</style>

<canvas id="myCanvas"></canvas>

<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.font = "32px Arial"; // フォント
    ctx.textAlign = "center"; // 横方向の位置を真ん中にする
    ctx.textBaseline = "middle"; // 縦方向の位置を真ん中にする
    ctx.fillStyle = "#8cff6f"; // 文字色
    var x = 0; // x座標
    // 文字を左から右に動かす(画面をクリア、文字を描画、文字の位置を変更する処理を繰り返し行う)
    // setIntervalで、100ミリ秒ごとに処理を実行する
    setInterval(function() {
        // 以前の描画を消去
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 文字を描画する(文字, x座標, y座標)
        ctx.fillText("Hello World!", x, canvas.height / 2);
        // x座標に加算して文字を右に動かす
        x += 10;
        // 左端までいったらx座標を初期化する
        if (x > canvas.width + 100) {
            x = 0;
        }
    }, 100);
</script>

Discussion

ログインするとコメントできます