我试图通过鼠标定义一个矩形,在一个html5画布上绘制一个椭圆。我可以这样做,但使用我当前的方法,椭圆不适合我的边界矩形。我如何绘制这个椭圆,使其完全适合它的边界矩形?
这就是我所拥有的:
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
,然后再stroke
或fill
,以便查看它们,与其他任何路径元素一样。
答案 1 :(得分: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();
}