【问题标题】:Canvas - how to fill all circles at once, not one by one画布 - 如何一次填充所有圆圈,而不是一个一个
【发布时间】:2016-06-26 06:40:25
【问题描述】:

我有while循环一一画圈:

actx.shadowColor = 'rgba(0, 0, 0, 1)';
while (len--) {
   var point = data[len];

   actx.beginPath();
   actx.arc(point[0] - 15000, point[1] - 15000, 10, 0, Math.PI * 2);
   actx.closePath();
   actx.fill();
}

对我来说似乎有点慢,所以我在想如何优化它。我发现fill()函数占用的时间最长,所以我试着把它放在循环之后,但它只画了最后一个圆圈。

  1. 有什么方法可以一次填满所有的圆圈吗?
  2. 或者还有其他更快的方法吗?

【问题讨论】:

    标签: javascript html html5-canvas


    【解决方案1】:

    一些优化:

    • 在循环外计算一次 Math.PI*2,而不是每次在循环内计算
    • 将 beginPath 放在循环之前
    • 在循环内绘制圆弧 + closePath(您在循环内创建了许多圆形子路径)
    • 在循环之后放置填充以一次绘制所有子路径

    重构代码:

    // test data
    var data=[];
    for(var i=0;i<100;i++){data.push([i+15000+30,i+15000+30]);}
    
    // calculate PI2 outside the loop instead of every time in the loop
    var PI2=Math.PI*2;
    
    actx.shadowColor = 'rgba(0, 0, 0, 1)';
    
    // beginpath once outside the loop
    actx.beginPath();
    var len=data.length;
    while (len--) {
       var point = data[len];
    
       // draw
       actx.arc(point[0]-15000, point[1]-15000,10,0,PI2);
       // closepath will close the current circle's subpath
       actx.closePath();
    
    }           
    // just fill once when done drawing
    actx.fill();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      相关资源
      最近更新 更多