星のきらめき

星のきらめき | ひまあそび-ミニゲーム hi0a.com

view source

JavaScript

document.title = '星のきらめき';

let { canvas, ctx, cx, cy, w, h, min, demo } = readyCanvas();
canvas.style.backgroundColor = '#000';




const numStars = 120;
const stars = [];

class Star {
  constructor() {
    this.reset();
  }

  reset() {
    this.x = Math.random() * canvas.width;
    this.y = Math.random() * canvas.height;
    this.size = Math.random() * min/80 + min/80;
    this.alpha = Math.random();
    this.delta = Math.random() * 0.02 + 0.01;
    this.rotation = Math.random() * Math.PI * 2;
  }

  update() {
    this.alpha += this.delta;
    if (this.alpha <= 0 || this.alpha >= 1) {
      this.delta = -this.delta;
    }
  }

  draw() {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.rotation);
    ctx.globalAlpha = this.alpha;
    drawStar(ctx, 0, 0, 4, this.size, this.size / 8);
    ctx.fillStyle = 'white';
    ctx.fill();
    ctx.restore();
  }
}

// 星型(4-5芒星)を描く関数
function drawStar(ctx, x, y, points, outerRadius, innerRadius) {
  const step = Math.PI / points;
  ctx.beginPath();
  for (let i = 0; i < 2 * points; i++) {
    const radius = i % 2 === 0 ? outerRadius : innerRadius;
    const angle = i * step;
    ctx.lineTo(x + Math.cos(angle) * radius, y + Math.sin(angle) * radius);
  }
  ctx.closePath();
}

// 星の生成
function setStar(){
  stars.length = 0;
  for (let i = 0; i < numStars; i++) {
    stars.push(new Star());
  }
}
setStar();

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

animate();

window.addEventListener('resize', () => {
    setTimeout(() => {
        setStar();
    }, 1);
});

CSS

HTML

ページのソースを表示 : Ctrl+U , DevTools : F12

view-source:https://hi0a.com/game/canvas-star/

ABOUT

hi0a.com 「ひまあそび」は無料で遊べるミニゲームや便利ツールを公開しています。

プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。

必要な機能の関数をコピペ利用したり勉強に活用できます。

プログラムの動作サンプル結果は画面上部に出力表示されています。

環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。

画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。

仕様変更、API廃止等、実験途中で動かないページもあります。