歪んだ円を描く

歪んだ円を描く | ひまあそび-ミニゲーム hi0a.com

view source

JavaScript

document.title = '歪んだ円を描く';

var canvas = document.createElement('canvas');
var w = document.body.clientWidth;
var h = document.body.clientHeight;
var min = Math.min(w,h);

canvas.setAttribute('width',w);
canvas.setAttribute('height',h);
let demo = document.getElementById('demo');
demo.appendChild(canvas);

const ctx = canvas.getContext("2d");

const cx = w/2;
const cy = h/2;
const baseRadius = w/8;

//ジグザグすぎる
function drawCircleRan(cx,cy){ 
  const points = 100;
  ctx.beginPath();

  for (let i = 0; i <= points; i++) {
    const angle = (i / points) * 2 * Math.PI;
    const noise = Math.random() * 20 - 10; // -10〜+10のランダムな歪み
    const radius = baseRadius + noise;
    const x = cx + radius * Math.cos(angle);
    const y = cy + radius * Math.sin(angle);

    if (i === 0) {
      ctx.moveTo(x, y);
    } else {
      ctx.lineTo(x, y);
    }
  }

  ctx.closePath();
  ctx.stroke();
}


//規則的すぎる
function drawCircleSin(cx,cy){

  const points = 100;
  let time = 0;
  function draw() {

    ctx.beginPath();

    for (let i = 0; i <= points; i++) {
      const angle = (i / points) * 2 * Math.PI;

      // sin波による滑らかなゆらぎ
      const wave = Math.sin(angle * 4 + time) * 10;
      const radius = baseRadius + wave;

      const x = cx + radius * Math.cos(angle);
      const y = cy + radius * Math.sin(angle);

      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    }

    ctx.closePath();
    ctx.stroke();

    time += 0.05;
    //requestAnimationFrame(draw);
  }

  draw();
}

//自然に滑らかな歪み
function drawOrganicCircle(cx, cy) {
  const points = 200;
  const variation = 15;

  // 周波数は整数、phaseはゼロにして閉じる形に
  const layers = Array.from({ length: 4 }, () => ({
    freq: Math.floor(Math.random() * 4 + 1), // 1〜4の整数周波数
    amp: Math.random() * 0.5 + 0.5,          // 振幅
  }));

  ctx.beginPath();
  for (let i = 0; i <= points; i++) {
    const angle = (i / points) * 2 * Math.PI;

    // 合成ノイズ
    let offset = 0;
    for (let l of layers) {
      offset += Math.sin(angle * l.freq) * l.amp;
    }

    const radius = baseRadius + offset * variation;
    const x = cx + radius * Math.cos(angle);
    const y = cy + radius * Math.sin(angle);

    if (i === 0) ctx.moveTo(x, y);
    else ctx.lineTo(x, y);
  }

  ctx.closePath();
  ctx.stroke();
}





drawCircleRan(w*1/6,h*1/4);
drawCircleSin(w*3/6,h*1/4);
drawOrganicCircle(w*5/6,h*1/4);
drawOrganicCircle(w*1/6,h*3/4);
drawOrganicCircle(w*3/6,h*3/4);
drawOrganicCircle(w*5/6,h*3/4);

CSS

HTML

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

view-source:https://hi0a.com/demo/-js/js-canvas-circle-distorted/

ABOUT

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

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

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

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

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

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

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