简体   繁体   中英

How to spawn a random amount (with limits) of these "stars"(ellipses)?

function setup() {
  createCanvas(5000, 2100);
  randomX = random(100, 1000)
  randomY = random(100, 1000)
  randomSpeed = random(1, 10)
  randomSize = random(10, 100)
}
 function draw() {
      background(0);
      fill(255)
      ellipse(randomX, randomY, randomSize)
      randomX = randomX + randomSpeed
      if (randomX > 5000) {
        randomX = 0
          }
}

In the draw() function, there is an ellipse i need to be drawn on the canvas a random amount of times, WITH A LIMIT, on the canvas to make the starry night effect, how do I do that?

If I understand you right, you want to draw a bunch of ellipses on the canvas in random positions. I've answered assuming that's what you're asking. Apologies if that's not what you want.

What this program does is create two lists that hold data about the ellipses. In setup() we choose a random number of ellipses to draw. We make that many random sizes and positions then put them into the lists. When it comes time to draw the ellipses, we loop through the lists containing information about them and use that to draw a number of ellipses.


const ellipseMinSize = 1;
const ellipseMaxSize = 10;
const ellipseMinAmount = 10;
const ellipseMaxAmount = 100;

// Create some lists so we can remember where the ellipses are and how big they are
var ellipseSizes = [];
var ellipsePositions = [];

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

    // Choose an amount of ellipses to make
    var ellipseAmount = random(ellipseMinAmount, ellipseMaxAmount);

    for (var i = 0; i < ellipseAmount; i ++) {
        // Choose a random size and position, then remember those
        var ellipseSize = random(ellipseMinSize, ellipseMaxSize);
        var ellipsePosition = createVector(random(0, width), random(0, height));
        ellipseSizes.push(ellipseSize);
        ellipsePositions.push(ellipsePosition);
    }
}

function draw() {
    background(0);
    fill(255);

    // Then loop through the remembered positions and sizes, and draw an ellipse with those parameters
    for (var i = 0; i < ellipseSizes.length; i ++) {
        var ellipseSize = ellipseSizes[i];
        var ellipsePosition = ellipsePositions[i];
        ellipse(ellipsePosition.x, ellipsePosition.y, ellipseSize, ellipseSize);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM