计算机图形学之画圆(中点画圆法、Bresenham画圆法)

参考学习了一些前辈的代码,总结了以下这个,感谢前人栽树,同时欢迎交流。

整个画圆利用了圆的八对称性,故只需画出八分之一圆就可利用对称性就可以画出整个圆。

  •   专门写了一个函数来画圆的点,其中(x0,y0)为圆心坐标,根据(x,y)来画出八对称点,DrawPixel()为绘制点的函数。
 function DrawCirclePoint(x0, y0, x, y, color) {
     DrawPixel(x0 + x, y0 + y, color); 
     DrawPixel(x0 + y, y0 + x, color);
     DrawPixel(x0 - x, y0 + y, color);
     DrawPixel(x0 - y, y0 + x, color);
     DrawPixel(x0 + x, y0 - y, color);
     DrawPixel(x0 + y, y0 - x, color);
     DrawPixel(x0 - x, y0 - y, color); 
     DrawPixel(x0 - y, y0 - x, color);
 }
  • 中点画圆法:
function MiddlePiontCircle(x0, y0, r, color) {
     var x = 0, y = r;
     var d = 1 - r;//使用e=d-0.25代替d
     sleep(1000);
     DrawCirclePoint(x0, y0, x, y, color);
     while (x <= y) {
         if (d < 0)
              d += 2 * x + 3;
         else {
              d += 2 * (x - y) + 5;
              y--;
          }
         x++;
         DrawCirclePoint(x0, y0, x, y, color);
      }
 }
  • Bresenham画圆算法
function BresenhamCircle(x0, y0, r, color) {
    var x = 0, y = r;
    var delta = 2 * (1 - r);
    var delta1, delta2, direction;
    while (y >= 0) {
        // sleep(1000);
        DrawCirclePoint(x0, y0, x, y, color);
        if (delta < 0) {
             delta1 = 2 * (delta + y) - 1;
             if (delta1 <= 0) direction = 1;
             else direction = 2;
         }
         else if (delta > 0) {
              delta2 = 2 * (delta - x) - 1;
              if (delta2 <= 0) direction = 2
              else direction = 3;
         }
        else
              direction = 2;
        switch (direction) {
              case 1: 
                  x++;
                  delta += 2 * x + 1;
                  break;
              case 2: 
                  x++;
                  y--;
                  delta += 2 * (x - y + 1);
                  break;
              case 3: 
                  y--;
                  delta += (-2 * y + 1);
                  break;
         }
     }
 }

 

你可能感兴趣的:(Web)