简体   繁体   中英

Select object from array at random

I'm trying to make a function or an if condition that picks one of three circles every second randomly.

The context is that I want to make an animation and the circles should run from right canvas height/2 to left. Every second a new circle should drawn on the canvas but the other circles that were drawn before the new one shouldn't become deleted. How can I accomplish that?

var circle1={color: blue};
var circle2={color: yellow};
var circle3={color: orange};

var circles=[];
circles.push(circle1);
circles.push(circle2);
circles.push(circle3);

function drawCircle(circle){
      ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, x*5, 0, 2*Math.PI, false);
      ctx.fillStyle = 'circle.color';
      ctx.fill();

  }

This function returns a random element from an array:

function getRandomElement(array) {
  if (array.length == 0) {
    return undefined;
  }
  return array[Math.floor(Math.random() * array.length)];
}

To see it in action, run this snippet:

 function getRandomElement(array) { if (array.length == 0) { return undefined; } return array[Math.floor(Math.random() * array.length)]; } var circles = [ {color: 'yellow'}, {color: 'orange'}, {color: 'red'}, {color: 'pink'}, {color: 'blue'}, {color: 'green'}, {color: 'purple'}, {color: 'brown'} ]; document.write('random circle: ' + JSON.stringify(getRandomElement(circles))); 

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