2013-04-09 50 views
3

我在HTML5畫布使用此功能(How to draw an oval in html5 canvas?)繪製一個橢圓:如何繪製用三次貝塞爾曲線繪製的橢圓的一部分?

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

然後,我得到所有這些值,並將其發送給我的Android應用程序。在那裏,我使用Path類的cubicTo方法繪製相同的橢圓。爲此,我只使用上面的函數的相同參數,它像魅力一樣工作。

但是現在,我只能畫出這個橢圓的一部分,而我在Google上沒有找到任何可以幫助我解決這個問題的東西。我想要做的是,具有這種第一橢圓:

enter image description here

我希望能夠利用這些圖像:

enter image description here

enter image description here

enter image description here

我該怎麼做這種事?

回答

0

我得做一個最簡單的方法。我只是在Web應用程序中使用Bezier保護程序繪製一個橢圓。然後,我得到centerX,centerY,橢圓的寬度和高度,並將它們傳遞給我的android應用程序。

在我的Android應用程序中,我可以使用drawOval方法繪製Web中繪製的橢圓。有了這個,我可以使用drawArcs方法繪製橢圓的圓弧,該方法接收一個橢圓作爲參數。

+0

可能值得編輯您的帖子以指出哪些API可供您在Android上無法在網上使用(canvas2d沒有橢圓形drawArc atm,例如只有圓形) – 2013-04-19 11:47:35

1

看看http://pomax.github.io/bezierinfo/#circles_cubic - 它討論了圓弧的這個問題(控制點的值以圓弧角表示,位於剖面的底部),但它們之間的唯一區別是旋轉+縮放比例爲1的尺寸。如果你理解了圓形近似,你也可以得到橢圓近似。

0

除了所有數學的東西,你可以簡單地使用裁剪:

canvas.save(); 
canvas.clipRect(mYourTargetRect); 
// draw your arc/circle/object/oval/whatever here 
canvas.restore(); 
+0

嘿,很真實。 – 2013-04-09 21:10:15

0

Chrome支持CanvasRenderingContext2D.prototype.ellipse繪製橢圓或橢圓弧的方法。但其他瀏覽器不支持橢圓方法。可以使用canvas-5-polyfill來提供橢圓方法。

或者只是寫一些JS代碼:

if (CanvasRenderingContext2D.prototype.ellipse == undefined) { 
    CanvasRenderingContext2D.prototype.ellipse = function(x, y, radiusX, radiusY, rotation, startAngle, endAngle, antiClockwise) { 
    this.save(); 
    this.translate(x, y); 
    this.rotate(rotation); 
    this.scale(radiusX, radiusY); 
    this.arc(0, 0, 1, startAngle, endAngle, antiClockwise); 
    this.restore(); 
    } 
} 
相關問題