花びらが舞い落ちる
花びらが舞い落ちる | ひまあそび-ミニゲーム hi0a.com
view source
JavaScript
document.title = '花びらが舞い落ちる';
let { canvas, ctx, cx, cy, w, h, min, demo } = readyCanvas();
// 花びらクラス
class Petal {
constructor() {
this.reset();
}
reset() {
this.type = Math.floor(Math.random() * 2);
this.x = Math.random() * canvas.width;
this.y = Math.random() * -canvas.height;
this.radius = 6 + Math.random() * min/120;
this.speedY = 1 + Math.random() * 2;
this.speedX = Math.random() * 1 - 0.5;
this.angle = Math.random() * Math.PI * 2;
this.spin = Math.random() * 0.02 - 0.01;
this.opacity = 0.6 + Math.random() * 0.4;
}
update() {
this.x += this.speedX + Math.sin(this.angle) * 0.5;
this.y += this.speedY;
this.angle += this.spin;
if (this.y > canvas.height || this.x < -50 || this.x > canvas.width + 50) {
this.reset();
}
}
draw(ctx) {
if(this.type === 0){
//楕円タイプ
ctx.save();
ctx.beginPath();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.scale(1.2, 0.6);
ctx.fillStyle = `rgba(255, 182, 193, ${this.opacity})`; // 淡いピンク
ctx.arc(0, 0, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
} else {
//円弧タイプ
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
const r = this.radius*2;
ctx.beginPath();
// 始点: (0, r)
ctx.moveTo(0, r);
// 円弧1: (0, r) → (r, 0) を中心 (0, 0) の円弧で接続(反時計回り)
ctx.arc(0, 0, r, Math.PI * 0.5, 0, true);
// 円弧2: (r, 0) → (0, r) を中心 (r, r) の円弧で接続(反時計回り)
ctx.arc(r, r, r, Math.PI * 1.5, Math.PI, true);
ctx.closePath();
ctx.fillStyle = `rgba(255, 182, 193, ${this.opacity})`;
ctx.fill();
ctx.restore();
}
}
}
const petals = [];
for (let i = 0; i < 300; i++) {
petals.push(new Petal());
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
petals.forEach(petal => {
petal.update();
petal.draw(ctx);
});
requestAnimationFrame(animate);
}
animate();
CSS
HTML
ページのソースを表示 : Ctrl+U , DevTools : F12
view-source:https://hi0a.com/game/canvas-flower-petal/
ABOUT
hi0a.com 「ひまあそび」は無料で遊べるミニゲームや便利ツールを公開しています。
プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。
必要な機能の関数をコピペ利用したり勉強に活用できます。
プログラムの動作サンプル結果は画面上部に出力表示されています。
環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。
画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。
仕様変更、API廃止等、実験途中で動かないページもあります。