無数の乱数移動軌跡で染みを再現

無数の乱数移動軌跡で染みを再現 | ひまあそび-ミニゲーム hi0a.com

view source

JavaScript

document.title = '無数の乱数移動軌跡で染みを再現'


let { canvas, ctx, cx, cy, w, h, min, demo } = readyCanvas();


class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  move() {
    this.x += Math.random() * 4 - 2; // -2〜2のランダム移動
    this.y += Math.random() * 4 - 2;

    // キャンバス外に出たら反対側にワープ
    if (this.x < 0) this.x = w;
    if (this.x > w) this.x = 0;
    if (this.y < 0) this.y = h;
    if (this.y > h) this.y = 0;
  }

  draw(ctx) {
    ctx.beginPath();
    ctx.arc(this.x, this.y, 0.8, 0, Math.PI * 2);
    ctx.fill();
  }
}



let points = [];
const numPoints = 500;

setStage();

ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'; // 線の色

 // n分後に塗る色をランダム変更
setTimeout(() => {
  chengeColor();
}, 10*60*1000);


function chengeColor() {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  ctx.fillStyle = `rgba(${r}, ${g}, ${b}, 0.1)`;
  //console.log(`色変更: rgba(${r}, ${g}, ${b}, 0.1)`);
}

document.addEventListener('click', chengeColor);

function animate() {
  for (let point of points) {
    point.move();
    point.draw(ctx);
  }
  requestAnimationFrame(animate);
}
animate();

function setStage(){
  w = canvas.width;
  h = canvas.height;
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, w, h);
  points = [];
  for (let i = 0; i < numPoints; i++) {
    points.push(new Point(Math.random() * w, Math.random() * h));
  }
}


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

CSS

HTML

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

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

ABOUT

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

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

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

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

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

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

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