JavaScriptでCanvasに雨を降らせるギミックサンプル【jQuery無し】

JavaScript

雨を降らせてみました。どちらかというと雪のようにも感じますが……色々数値をいじれば遠近感が出たり、線状(雨の起動)にしたり汎用的かもしれません。使う機会があれば是非参考にしてください。

<canvas id="myCanvas"></canvas>
<script>
  // Canvasの要素を取得する
  var canvas = document.getElementById("myCanvas");

  // Canvasの描画コンテキストを取得する
  var ctx = canvas.getContext("2d");

  // 雨粒の数
  var drops = [];

  // 雨粒の設定
  function RainDrop() {
    // 雨粒の初期位置をランダムに設定
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * -canvas.height;

    // 雨粒の落下スピードをランダムに設定
    this.speed = Math.random() * 50 + 5;

    // 雨粒の半径をランダムに設定
    this.radius = Math.random() * 0.2 + 1;

    // 雨粒を描画する関数
    this.draw = function () {
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
      ctx.fillStyle = "#FFFFFF";
      ctx.fill();
      ctx.closePath();
    }
  }

  // 雨粒を追加する関数
  function addRainDrop() {
    drops.push(new RainDrop());
  }

  // 雨粒を更新する関数
  function updateRainDrops() {
    for (var i = 0; i < drops.length; i++) {
      // 雨粒を落下させる
      drops[i].y += drops[i].speed;

      // 雨粒がCanvasの下端に達したら、画面上から消す
      if (drops[i].y > canvas.height) {
        drops.splice(i, 1);
        i--;
      }
    }
  }

  // 雨粒を描画する関数
  function drawRainDrops() {
    for (var i = 0; i < drops.length; i++) {
      drops[i].draw();
    }
  }

  // アニメーションを開始する関数
  function startAnimation() {
    setInterval(function () {
      // Canvasをクリアする
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 雨粒を追加する
      addRainDrop();

      // 雨粒を更新する
      updateRainDrops();

      // 雨粒を描画する
      drawRainDrops();
    }, 1);
  }

  // アニメーションを開始する
  startAnimation();
</script>
<style>
  canvas#myCanvas {
    background: #333;
    width: 100%;
    height: 300px;
  }
</style>
タイトルとURLをコピーしました