JavaScriptとCanvasを使ってウェブサイトに雨のエフェクトを追加する方法

ウェブサイトにインタラクティブなエフェクトを追加することで、ユーザーの体験を豊かにすることができます。今回は、JavaScriptとHTML5のCanvasを使って、サイトに雨が降っているようなエフェクトを実装する方法をご紹介します。

サンプルはこちら

雨のエフェクトサンプル


ステップ1: 基本的なHTMLのセットアップ

まず、HTMLファイルを作成し、Canvas要素を追加します。
このCanvas要素は、JavaScriptで雨のエフェクトを描画するための領域となります。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rain Effect</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
background: #000;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="rainCanvas"></canvas>
<script src="rain.js"></script>
</body>
</html>

このHTMLでは、<canvas>要素を使って描画領域を定義しています。CSSスタイルでは、全体の背景色を黒に設定し、Canvas要素が画面全体をカバーするようにしています。


ステップ2: JavaScriptで雨のエフェクトを実装

次に、rain.jsという名前のJavaScriptファイルを作成し、Canvas上に雨を描画するコードを記述します。

document.addEventListener('DOMContentLoaded', function () {
const canvas = document.getElementById('rainCanvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const numberOfDrops = 500;
const rainDrops = [];

function RainDrop() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.length = Math.random() * 20 + 1;
this.speed = Math.random() * 5 + 2;
this.opacity = Math.random() * 0.5 + 0.1;
}

RainDrop.prototype.draw = function () {
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.x, this.y + this.length);
ctx.strokeStyle = `rgba(174,194,224,${this.opacity})`;
ctx.lineWidth = 1;
ctx.lineCap = 'round';
ctx.stroke();
};

RainDrop.prototype.update = function () {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = -this.length;
this.x = Math.random() * canvas.width;
}
this.draw();
};

function init() {
for (let i = 0; i < numberOfDrops; i++) {
rainDrops.push(new RainDrop());
}
}

function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let drop of rainDrops) {
drop.update();
}
requestAnimationFrame(animate);
}

init();
animate();

window.addEventListener('resize', function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
});

このスクリプトでは、次のことを行っています。

  1. canvasctxを取得し、Canvasのサイズをウィンドウサイズに設定。
  2. 雨粒の数を定義し、雨粒の配列を初期化。
  3. RainDropクラスを作成し、雨粒の位置、長さ、速度、不透明度をランダムに設定。
  4. drawメソッドで雨粒を描画。
  5. updateメソッドで雨粒の位置を更新し、画面の下に到達したら上部に戻す。
  6. init関数で雨粒の初期化。
  7. animate関数でアニメーションを実行。
  8. ウィンドウのリサイズイベントに対応。

まとめ

この方法を使えば、簡単にウェブサイトに雨が降っているようなエフェクトを追加することができます。CanvasとJavaScriptを駆使して、視覚的に魅力的なエフェクトを作り出し、
ユーザーエクスペリエンスを向上させましょう。

この記事が役に立った場合は、是非シェアしてください。
また、他にも面白いエフェクトのアイデアがあればコメントで教えてください!

サンプルはこちら