「sakura.html」
<!DOCTYPE html>
<html lang=”ja”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<html>
<head>
<title>桜のアニメーション</title>
<style>
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
.petals-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.petal {
position: absolute;
top: -50px;
background: url(“https://i.imgur.com/tzH1w2f.png”) no-repeat;
width: 50px;
height: 50px;
animation: petal-fall 5s linear infinite;
opacity: 0;
}
@keyframes petal-fall {
0% {
opacity: 1;
transform: translateY(-50px) rotate(0deg);
}
100% {
opacity: 0;
transform: translateY(100vh) rotate(360deg);
}
}
</style>
</head>
<body>
<canvas id=”canvas”></canvas>
<div class=”petals-container”></div>
<script src=”scriptsk.js”></script>
</body>
</html>
.
「scriptsk.js」
// 花びらを表すオブジェクト
class Petal {
constructor(x, y, size, speed) {
this.x = x;
this.y = y;
this.size = size;
this.speed = speed;
this.angle = Math.random() * Math.PI * 2;
this.drift = Math.random() * 5;
}
update() {
this.y += this.speed;
this.x += Math.sin(this.angle) * this.drift;
// 画面外に出た花びらを再利用
if (this.y > window.innerHeight) {
this.y = Math.random() * -100;
this.x = Math.random() * window.innerWidth;
}
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fillStyle = “pink”;
ctx.fill();
}
}
// 花びらの配列
let petals = [];
// 初期化
function init() {
// キャンバスの設定
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 花びらを生成
for (let i = 0; i < 100; i++) {
let petal = new Petal(
Math.random() * window.innerWidth,
Math.random() * window.innerHeight,
Math.random() * 10 + 5,
Math.random() * 5 + 1
);
petals.push(petal);
}
// 描画
function draw() {
// 画面をクリア
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
// 花びらを更新して描画
for (let i = 0; i < petals.length; i++) {
petals[i].update();
petals[i].draw(ctx);
}
// 60fpsで再帰的に描画
requestAnimationFrame(draw);
}
// 描画を開始
draw();
}
// 初期化
init();
.