2012-10-11 73 views
0

我想通过鼠标定义一个矩形,将一个椭圆绘制到html5画布上。我可以做到这一点,但使用我目前的方法,椭圆不适合我的边界矩形。我如何绘制这个椭圆,使它完全适合它的边界矩形?可调整大小的椭圆html5 canvas

以下是我有:

var a1x = self.x; 
    var a1y = self.y - self.h/2; 

    var a2x = self.x; 
    var a2y = self.y + self.h/2; 

    var c1x = self.x + self.w/2; 
    var c1y = self.y - self.h/2; 
    var c2x = self.x + self.w/2; 
    var c2y = self.y + self.h/2; 

    var c3x = self.x - self.w/2; 
    var c3y = self.y + self.h/2; 
    var c4x = self.x - self.w/2; 
    var c4y = self.y - self.h/2; 

    context.beginPath(); 
    context.moveTo(a1x, a1y); 

    context.bezierCurveTo(
     c1x, c1y, 
     c2x, c2y, 
     a2x, a2y 
    ); 

    context.bezierCurveTo(
     c3x, c3y, 
     c4x, c4y, 
     a1x, a1y 
    ); 

    context.fillStyle = "red"; 
    context.fill(); 
    context.closePath(); 
    context.strokeRect(this.x - this.w/2, this.y - this.h/2, this. w, this.h); 
+0

你能提供一个小提琴演示吗? –

回答

0
CanvasRenderingContext2D.prototype.ellipse = 
    CanvasRenderingContext2D.prototype.ellipse || 
     function(x, y, width, height) 
     { 
      this.save(); 
      this.translate(x - width/2, y - height/2); 
      this.scale(width, height); 
      this.arc(0, 0, 1, 0, 2 * Math.PI, false); 
      this.restore(); 
     }; 

CanvasRenderingContext2D.prototype.circle = 
    CanvasRenderingContext2D.prototype.circle || 
     function(x, y, radius) 
     { 
      this.arc(x, y, radius, 0, 2 * Math.PI, false); 
     }; 

必须后才能调用beginPath之前和strokefill看到他们,与任何其他路径元素。

+0

看起来不错,谢谢你的回复 – weichsem

+0

'ellipse'的定义不符合[规格](http://www.w3.org/html/wg/drafts/2dcontext/html5_canvas/#dom-context-2d -椭圆)。不过,我不知道这个答案是否给出了不同的规格。 – MaxArt

0

此函数可能对每个想要将椭圆绘制成矩形的人有所帮助。

/** 
* Draws ellipse which fits into rectangle defined by 
* start point x,y and endpoint xe,ye. 
* 
* @param {CanvasRenderingContext2D} ctx 
* @param {Number} x 
* @param {Number} y 
* @param {Number} xe 
* @param {Number} ye 
*/ 
function ellipse(ctx, x, y, xe, ye) 
{ 
    ctx.save(); 
    ctx.beginPath(); 
    var rx = (xe - x)/2; 
    var ry = (ye - y)/2; 
    ctx.translate(x + rx, y + ry); 
    rx = Math.abs(rx); 
    ry = Math.abs(ry); 
    if (rx < ry) 
    { 
     ctx.scale(1, Math.abs(ry/rx)); 
     ctx.arc(1, 1, rx, 0, 2 * Math.PI, false); 
    } 
    else 
    { 
     ctx.scale(Math.abs(rx/ry), 1); 
     ctx.arc(1, 1, ry, 0, 2 * Math.PI, false); 
    } 
    ctx.restore(); 
    ctx.stroke(); 
}