--- title: CanvasRenderingContext2D.ellipse() slug: Web/API/CanvasRenderingContext2D/ellipse tags: - API - Canvas - CanvasRenderingContext2D translation_of: Web/API/CanvasRenderingContext2D/ellipse ---
CanvasRenderingContext2D
.ellipse()
是 Canvas 2D API 添加椭圆路径的方法。椭圆的圆心在(x,y)位置,半径分别是radiusX 和 radiusY ,按照anticlockwise(默认顺时针)指定的方向,从 startAngle 开始绘制,到 endAngle 结束。
void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise);
x
y
radius
Xradius
Yrotation
startAngle
endAngle
anticlockwise
{{optional_inline}}true
,逆时针方向绘制椭圆 (逆时针), 反之顺时针方向绘制。ellipse
方法这是一段绘制椭圆的简单的代码片段。
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.setLineDash([]);
ctx.beginPath();
ctx.ellipse(100, 100, 50, 75, 45 * Math.PI/180, 0, 2 * Math.PI); //倾斜45°角
ctx.stroke();
ctx.setLineDash([5]);
ctx.moveTo(0,200);
ctx.lineTo(200,0);
ctx.stroke();
修改下面的代码并在线查看 canvas 的变化(如果椭圆没有绘制,请在兼容性列表中检查你的浏览器是否支持):
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.setLineDash([]); ctx.beginPath(); ctx.ellipse(100, 100, 50, 75, 45 * Math.PI/180, 0, 2 * Math.PI); //倾斜45°角 ctx.stroke(); ctx.setLineDash([5]); ctx.moveTo(0,200); ctx.lineTo(200,0); ctx.stroke();</textarea>
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas);
{{ EmbedLiveSample('Playable_code', 700, 360) }}
Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-ellipse", "CanvasRenderingContext2D.ellipse")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.CanvasRenderingContext2D.ellipse")}}