canvas 上的 pic 随机画圈功能

pic random drawcircle function on canvas

我创建了 3 个函数,其中在 canvas 上绘制了一个圆圈。现在我希望 3 个函数之一在 draw() 函数中随机执行。我怎样才能意识到这一点?

    function drawcircle1()
      {
      var radius = x * 5;
        ctx.beginPath();
          ctx.arc(ballx * 100, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
          ctx.fillStyle = 'yellow';
          ctx.fill(); 
      }
    function drawcircle2()
      {
      var radius = x * 5;
        ctx.beginPath();
          ctx.arc(ballx * 100, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
          ctx.fillStyle = 'blue';
          ctx.fill(); 
      }
      function drawcircle3()
      {
      var radius = x * 5;
        ctx.beginPath();
          ctx.arc(ballx * 100, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
          ctx.fillStyle = 'orange';
          ctx.fill(); 
      }
    function draw() {   

   ctx.clearRect(0, 0, canvasWidth, canvasHeight);

      // here should the draw function pic random one of the 3 drawcircle functions


  }
var randomNum = Math.random();
if(randomNum < .333) drawcircle1();
else if(randomNum < .666) drawcircle2();
else drawcircle3();

将函数存储在数组中并生成随机索引:

function drawRandom(drawFunctions){
    //generate a random index
    var randomIndex = Math.floor(Math.random() * drawFunctions.length);

    //call the function
    drawFunctions[randomIndex]();
}

//store all functions in an array and call drawRandom
drawRandom([drawcircle1, drawcircle2, drawcircle3]);

I have added a jsfiddle。它演示了实现的想法


您还应该考虑进行小规模重构,因为除了颜色之外,所有功能都做同样的事情:

 function drawColoredCircle(color)
      {
      var radius = x * 5;
        ctx.beginPath();
          ctx.arc(ballx * 100, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
          ctx.fillStyle = color;
          ctx.fill(); 
      }
 function drawcircle1(){ drawColoredCircle('yellow'); }
 function drawcircle2(){ drawColoredCircle('blue'); }
 function drawcircle3(){ drawColoredCircle('orange'); }

这导致另一种可能的随机抽取解决方案:

function drawRandomColor(colors){
    //generate a random index
    var randomIndex = Math.floor(Math.random() * colors.length);
    var randomColor = colors[randomIndex];
    //call the function
    drawColoredCircle(randomColor);
}

drawRandomColor(["yellow", "blue", "orange"]);