1,使用lineTo画椭圆

function DrawEllipse(Canvas,O,OA,OB){
//画椭圆，例子：var B=new Array(150,150); DrawEllipse(hb,B,50,30);
with (Canvas){
var x=O[0]+OA;
var y=O[1];
moveTo(x,y);
for (var i=0;i<=360;i++){
var ii=i*Math.PI/180;
var x=O[0]+OA*Math.cos(ii);
var y=O[1]-OB*Math.sin(ii);
lineTo(x,y);
}
}
}

2,使用arc画圆，然后把他缩放成一个椭圆

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = 0;
var centerY = 0;

// save state
context.save();

// translate context
context.translate(canvas.width / 2, canvas.height / 2);

// scale context horizontally
context.scale(2, 1);

// draw circle which will be stretched into an oval
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

// restore to original state
context.restore()

3，使用贝赛尔曲线bezierCurveTo

function drawEllipse(ctx, x, y, w, h) {
var kappa = 0.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();
ctx.stroke();
}

4，使用两条贝赛尔曲线画出椭圆

//椭圆
CanvasRenderingContext2D.prototype.oval = function  (x, y, width, height) {
var k = (width/0.75)/2,
w = width/2,
h = height/2;
this.beginPath();
this.moveTo(x, y-h);
this.bezierCurveTo(x+k, y-h, x+k, y+h, x, y+h);
this.bezierCurveTo(x-k, y+h, x-k, y-h, x, y-h);
this.closePath();
return this;
}

贝塞尔控制点x=(椭圆宽度/0.75)/2

原文.转载请保留.

posted on 2013-01-09 10:11  十年灯  阅读(2074)  评论(7编辑  收藏

• 随笔 - 34
• 文章 - 1
• 评论 - 161