2014-04-10 126 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);