0

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();

  }

1 Answer 1

3

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)));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.