Finding all the points within a circle in 2D space

前端 未结 7 1800
自闭症患者
自闭症患者 2021-02-13 12:58

I am representing my 2D space (consider a window), where each pixel is shown as a cell in a 2D array. i.e. a 100x100 window is represented by the array of same dimensions.

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 14:02

    For getting a list of all points within a circle you should use:

    var radius = 100, r2 = radius * radius;
    var circle = [];
    for (var dx = -radius; dx <= radius; dx++) {
      var h = Math.sqrt(r2 - dx * dx) | 0;
      for (var dy = -h; dy <= h; dy++) {
        circle.push([dx, dy])
      }
    }
    

    See http://jsperf.com/circles/2 for profiling against the other solutions here.

提交回复
热议问题