【问题标题】:pic random drawcircle function on canvas画布上的 pic 随机 drawcircle 函数
【发布时间】:2015-08-24 19:21:46
【问题描述】:

我创建了 3 个函数,在画布上绘制了一个圆圈。现在我希望 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


  }

【问题讨论】:

    标签: javascript html canvas draw


    【解决方案1】:

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

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

    【讨论】:

    • 这样所有三个圆圈都绘制在画布上:(
    • 我添加了一个 jsfiddle,它展示了我刚刚发布的代码。只需用您的 drawcircle 方法替换“dummyFunctions”
    【解决方案2】:
    var randomNum = Math.random();
    if(randomNum < .333) drawcircle1();
    else if(randomNum < .666) drawcircle2();
    else drawcircle3();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2020-05-21
      • 1970-01-01
      • 2018-06-30
      相关资源
      最近更新 更多