the relation of the bezier Curve and ellipse?

前端 未结 5 2208
南笙
南笙 2020-12-18 05:03

I want to draw a oval in html5 canvas,and i found a good method for it in stackoverflow.but I have another quesition.

function drawEllipse(ctx, x, y, w, h) {         


        
5条回答
  •  渐次进展
    2020-12-18 05:54

    Big thanks to BKH. I used his code with two bezier curves to complete my ellipse drawing with any rotation angle. Also, I created an comparison demo between ellipses drawn by bezier curves and native ellipse() function (for now implemented only in Chrome).

    function drawEllipseByBezierCurves(ctx, x, y, radiusX, radiusY, rotationAngle) {
    var width_two_thirds = radiusX * 4 / 3;
    
    var dx1 = Math.sin(rotationAngle) * radiusY;
    var dy1 = Math.cos(rotationAngle) * radiusY;
    var dx2 = Math.cos(rotationAngle) * width_two_thirds;
    var dy2 = Math.sin(rotationAngle) * width_two_thirds;
    
    var topCenterX = x - dx1;
    var topCenterY = y + dy1;
    var topRightX = topCenterX + dx2;
    var topRightY = topCenterY + dy2;
    var topLeftX = topCenterX - dx2;
    var topLeftY = topCenterY - dy2;
    
    var bottomCenterX = x + dx1;
    var bottomCenterY = y - dy1;
    var bottomRightX = bottomCenterX + dx2;
    var bottomRightY = bottomCenterY + dy2;
    var bottomLeftX = bottomCenterX - dx2;
    var bottomLeftY = bottomCenterY - dy2;
    
    ctx.beginPath();
    ctx.moveTo(bottomCenterX, bottomCenterY);
    ctx.bezierCurveTo(bottomRightX, bottomRightY, topRightX, topRightY, topCenterX, topCenterY);
    ctx.bezierCurveTo(topLeftX, topLeftY, bottomLeftX, bottomLeftY, bottomCenterX, bottomCenterY);
    ctx.closePath();
    ctx.stroke();
    

    }

提交回复
热议问题