マウスをクリックしている間だけ動くおみくじ

スポンサーリンク

サンプル動画

動作プログラムはこちら

  <!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">
      <title>おみくじ</title>

      <script>

        // おみくじの内容
const omikuji = ["大吉", "吉", "中吉", "小吉", "末吉", "凶"];
// おみくじの結果
let omikujiResult;

function setup() {
  createCanvas(300, 300);

  // 文字の基準点を上下左右の中央に
  textAlign(CENTER, CENTER);
  // 文字の大きさの設定
  textSize(100);

  // おみくじの結果をランダムにセット
  omikujiResult = random(omikuji);
}

function draw() {
  background("#e02020");

  fill("#FFFFFF");
  stroke("#FFFFFF");
  
  // おみくじの結果を表示
  text(omikujiResult, width / 2, height / 2);

  // クリックされている間の処理
  if (mouseIsPressed == true) {
    // おみくじの結果をランダムにセット
    omikujiResult = random(omikuji);
  }
}
    </script>

    </head>
  <body>
      
  </body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>
  </html>

コードの解説

  • CDNからp5.jsを読み込む。
  • createCanvasでキャンバスサイズを指定
  • 変数omikujiに配列を格納しrandom()関数でランダムに結果を取り出す
  • if (mouseIsPressed == true) {○○} で「クリックされている間○○をする」という処理
  • 高速に動いて見えるのは、 mouseIsPressed == true が高速で繰り返されるから(だと思う)

コード改良(Qiitaコメント)

Qiitaコメントで改良プログラムを教えて頂いた⇒詳細はこちら
p5.jsを使わずjavascriptだけで作れるらしい(動作確認済)

<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<style>
.v {
  width: 300px;
  height: 300px;
  background-color: #e02020;
  color: white;
  font-size: 100px;
  display: flex;
  align-content: center;
  justify-content: center;
  flex-wrap: wrap;
  user-select: none;
}
</style>
</head>
<body>
<div class='v'></div>
<script>
'use strict';

const variation = [
  { name: '大吉', rate: 16},
  { name: '吉'  , rate: 35},
  { name: '中吉', rate:  4},
  { name: '小吉', rate:  6},
  { name: '末吉', rate: 10},
  { name: '凶'  , rate: 29},
];

let intervalId;

const d = document.querySelector('.v');

const threshold = [];
variation.forEach((v, i) => threshold[i] = v.rate + (i > 0 ? threshold[i - 1] : 0));
const total = threshold.at(-1);

const pickup = () => {
  const r = Math.random() * total;
  d.textContent = variation[threshold.indexOf(Math.min(...threshold.filter(e => e > r)))].name;
};
pickup();

addEventListener('mousedown', () => intervalId = setInterval(pickup, 1000 / 60));
addEventListener('mouseup', () => clearInterval(intervalId));
</script>
</body>

プログラム補足

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
> "a"
> "b"
> "c"

const array1 = [5, 12, 8, 130, 44];
console.log(`${array1.at(2)}`);
> "8"
p5.js
スポンサーリンク
のんびりブログ

コメント

タイトルとURLをコピーしました