html语言如何画椭圆,如何在HTML5画布上画一个椭圆?

Tammo提出了一个问题:How to draw an oval in html5 canvas?,或许与您遇到的问题类似。

updates:

scaling method can affect stroke width appearance

scaling method done right can keep stroke width intact

canvas has ellipse method that Chrome now supports

added updated tests to JSBin

JSBin Testing Example (updated to test other's answers for comparison)

Bezier - draw based on top left containing rect and width/height

Bezier with Center - draw based on center and width/height

Arcs and Scaling - draw based on drawing circle and scaling

Quadratic Curves - draw with quadraticstest appears to not draw quite the same, may be implementation

Canvas Ellipse - using W3C standard ellipse() methodtest appears to not draw quite the same, may be implementation

see Loktar's answer

Original:

If you want a symmetrical oval you could always create a circle of radius width, and then scale it to the height you want (edit: notice this will affect stroke width appearance - see acdameli's answer), but if you want full control of the ellipse here's one way using bezier curves.

var canvas = document.getElementById('thecanvas');

if(canvas.getContext)

{

var ctx = canvas.getContext('2d');

drawEllipse(ctx, 10, 10, 100, 60);

drawEllipseByCenter(ctx, 60,40,20,10);

}

function drawEllipseByCenter(ctx, cx, cy, w, h) {

drawEllipse(ctx, cx - w/2.0, cy - h/2.0, w, h);

}

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

var kappa = .5522848,

ox = (w / 2) * kappa, // control point offset horizontal

oy = (h / 2) * kappa, // control point offset vertical

xe = x + w, // x-end

ye = y + h, // y-end

xm = x + w / 2, // x-middle

ym = y + h / 2; // y-middle

ctx.beginPath();

ctx.moveTo(x, ym);

ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);

ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);

ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);

ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);

//ctx.closePath(); // not used correctly, see comments (use to close off open path)

ctx.stroke();

}

希望本文对你有帮助,欢迎支持JavaScript中文网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值