在JS中绘制具有厚度的轮廓椭圆

时间:2017-11-07 15:27:13

标签: javascript canvas drawing ellipse outline

我想在Javascript中绘制一个基本的轴对齐椭圆,而不提供Canvas / Context方法(它们添加了我不想要的抗锯齿!)

到目前为止,我的工作正常,但厚度仍然是错误的。

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

function setPixel(x, y, r, g, b)
{
  var index = (y * imageData.width + x) * 4;
  imageData.data[index + 0] = r;
  imageData.data[index + 1] = g;
  imageData.data[index + 2] = b;
  imageData.data[index + 3] = 255;
}

function drawEllipse(x1, y1, x2, y2, thickness, r, g, b)
{
  var radX = (x2 - x1) * 0.5;
  var radY = (y2 - y1) * 0.5;
  var cenX = (x1 + x2) * 0.5;
  var cenY = (y1 + y2) * 0.5;
  var aspectX = 1.0;
  var aspectY = 1.0;
  
  var radMax = Math.max(radX, radY);
  if (radX > radY)
    aspectY = radX / radY;
  else
    aspectX = radY / radX;
  
  for (var x = x1; x < x2; x++)
  {	
    for (var y = y1; y < y2; y++)
    {
      var dx = Math.abs(x - cenX) * aspectX;
      var dy = Math.abs(y - cenY) * aspectY;
      var d = Math.sqrt(dx*dx + dy*dy);
      var side1 = d < radMax && d > radMax - thickness;

      if (side1)
      	setPixel(x, y, r, g, b);
    }
  }
}

drawEllipse(0, 0, canvas.width - 1, canvas.height - 1, 20, 0, 0, 0);
ctx.putImageData(imageData, 0, 0);
#myCanvas { background: white; }
<canvas id="myCanvas" width="120" height="60"></canvas>

或者在JSBin上: https://jsbin.com/diwewimuya/edit?html,css,js,output

0 个答案:

没有答案