2014-04-10 91 views
0

我想要在canvas上绘制椭圆的高度。下面是我在画布上绘制椭圆的代码。在画布上绘制椭圆的高度

 function drawOval(startX, startY, endX, endY, strokeColor) { 
    x = endX; 
    y = endY; 
    context.beginPath(); 
    context.strokeStyle = strokeColor; 
    context.moveTo(startX, startY + (y - startY)/2); 
    context.bezierCurveTo(startX, startY, x, startY, x, startY + (y - startY)/2); 
    context.bezierCurveTo(x, y, startX, y, startX, startY + (y - startY)/2); 
    context.stroke(); 
    context.fillStyle = strokeColor; 
    context.fill(); 

} 

回答

0

我建议绘制椭圆以不同的方式:

  • 贝塞尔更复杂,性能饿
  • 贝塞尔没有画出准确的椭圆形(椭圆形)
  • 更难提取某些测量点而不使用手动公式。

要使用不同的方法是签名兼容,你有你能做什么:

function drawOval(startX, startY, endX, endY, strokeColor) { 

    var rx = (endX - startX) * 0.5, // get radius for x 
     ry = (endY - startY) * 0.5, // get radius for y 
     cx = startX + rx,   // get center position for ellipse 
     cy = startY + ry, 
     a = 0,      // current angle 
     step = 0.01,     // angle step 
     pi2 = Math.PI * 2; 

    context.beginPath(); 
    context.strokeStyle = strokeColor; 
    context.moveTo(cx + rx, cy);  // initial point at 0 deg. 

    for(; a < pi2; a += step) 
     context.lineTo(cx + rx * Math.cos(a), // create ellipse path 
         cy + ry * Math.sin(a)); 

    context.closePath();    // close for stroke 

    context.stroke(); 
    context.fillStyle = strokeColor; 
    context.fill(); 
} 

Live demo here

现在,您将得到高度(和宽度)简单地做:

var width = Math.abs(endX - startX), 
    height = Math.abs(endY - startY);