简体   繁体   English

如何生成这些“星星”(椭圆)的随机数量(有限制)?

[英]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?在 draw() function 中,有一个椭圆我需要在 canvas 上随机绘制几次,有限制地在 canvas 上绘制星夜效果,我该怎么做?

If I understand you right, you want to draw a bunch of ellipses on the canvas in random positions.如果我没理解错的话,您想在 canvas 上的随机位置绘制一串椭圆。 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.setup()中,我们选择随机数量的椭圆来绘制。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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