HTMLのcanvas要素とJavaScriptで泡が下から浮かんでくるアニメーションを作成!

HTMLのcanvas要素とJavaScriptで泡が下から浮かんでくるアニメーションを作成しました。

実際の表示

ソースコード例

HTMLソースコード例

<div class="canvas">
	<canvas id="bubbleCanvas"></canvas>
</div>

CSSソースコード例

canvas {
    width: 100%;
    background-color: #0a0a32;
}

JavaScriptソースコード例

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

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

    class Bubble {
        constructor() {
            this.x = Math.random() * canvas.width;
            this.y = canvas.height + Math.random() * canvas.height;
            this.radius = Math.random() * 20 + 10; //泡の半径を指定
            this.speed = Math.random() * 1 + 0.5; //泡が上昇するスピードを指定
            this.color = `hsla(${Math.random() * 360}, 100%, 50%, 0.8)`;
        }

        draw() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
            ctx.fillStyle = this.color;
            ctx.fill();
        }

        update() {
            this.y -= this.speed;
            if (this.y < -this.radius) {
                this.y = canvas.height + this.radius;
                this.x = Math.random() * canvas.width;
            }
            this.draw();
        }
    }

    const bubbles = [];
    for (let i = 0; i < 50; i++) { //泡が50個
        bubbles.push(new Bubble());
    }

    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        bubbles.forEach(bubble => bubble.update());
        requestAnimationFrame(animate);
    }

    animate();
});

まとめ

JavaScriptのソースコード内で「泡の大きさや数、スピード」を変更する箇所をコメントアウトしたので、色々試してみてください!

>お問い合わせはこちら

お問い合わせはこちら