你如何创建一个随机传播对象的JS代码

How do you create a JS code that randomly spreads objects

我正在制作一个您必须输入密码的简单代码,我想知道如何制作一个 随机分发文本 的代码。我尝试过使用push和pop方法。

let sumbit;
let input;
let element;
function setup() {
  createCanvas(400,400);

  sumbit = createButton('Submit');
  sumbit.mousePressed(button);

  input = createInput();
  input.position(20, 60);

  element = createElement('h2', 'What is the password : ');
  element.position(5, 10);

  textSize(32);
}


function button() {
  const password = input.value();
  if(password == "2010") {
    element.html('Your Correct! ' + ' The password was ' + password);
  
  } else {
    element.html('Your incorrect the password was : 2010');
  }
  
  input.value('');
html, body {
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sketch</title>

    <link rel="stylesheet" type="text/css" href="style.css">

    <script src="libraries/p5.min.js"></script>
    <script src="libraries/p5.sound.min.js"></script>
  </head>

  <body>
    <script src="sketch.js"></script>
  </body>
</html>

我想要使字母看起来像这样的代码。我会很感激一些建议,提前谢谢你。

您可以使用:

  • text() 渲染每个字符
  • random() 随机选择一个位置和角度(在一个范围内)
  • 使用其他与文本相关的函数来调整字符的外观,例如 textFont() to set a serif font and textSize()

这是一个带有注释的基本示例:

let stringOfCharacters = 'The quick brown fox jumped over the lazy dog.';
let numLetters = 1000;

function setup() {
  createCanvas(400, 400);
  background(255);
  fill(0);
  // set serif font
  textFont('Times New Roman');
  
  for(let i = 0 ; i < numLetters; i++){
    // pick the next character from the string above, looping from the start when the i counter is greater or equal to the number of characters in the string
    let character   = stringOfCharacters.charAt(i % stringOfCharacters.length);
    // 50-50 change of pick a case
    character = random(0.0, 1.0) > 0.5 ? character.toUpperCase() : character.toLowerCase();
    // pick a random position
    let randomX     = random(0, width);
    let randomY     = random(0, height);
    // pick a random size
    let size        = random(12, 24);
    // pick a random angle (rember, by default, angles in p5 are in radians (though can be changed with angleMode(DEGREES)))
    let randomAngle = random(0, TWO_PI);
    // isolate the coordinate system to apply the rotation
    push();
    rotate(randomAngle);
    textSize(size);
    text(character, randomX, randomY);
    pop();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

您可以选择 dice roll,而不是 50-50 随机条件,从矩形网格和稍微偏移的位置(这会减少交叉的可能性)开始,或任何其他随机方法。

p5 中还有一些选项可供您探索随机性,例如 Perlin noise() or randomGaussian() distribution