获取画布上绘制的椭圆的高度

get height of oval drawn on canvas

本文关键字:高度 绘制 获取      更新时间:2023-09-26

我想得到画布上绘制的椭圆的高度。下面是我在画布上绘制椭圆形的代码。

      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();
}

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

  • Bezier更为复杂,更需要性能
  • Bezier无法绘制精确的椭圆(椭圆)
  • 如果不使用手动公式,提取某些点进行测量会更加困难

要使用与您现有的签名兼容的不同方法,您可以执行以下操作:

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();
}

此处的实时演示

现在,您只需执行以下操作即可获得高度(和宽度):

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