CanvasRenderingContext2D: ellipse() 方法

Baseline 已廣泛支援

此功能已相當成熟,可在多種裝置和瀏覽器版本上執行。自 ⁨2016 年 8 月⁩ 起,所有瀏覽器均已提供此功能。

Canvas 2D API 的 CanvasRenderingContext2D.ellipse() 方法將一個橢圓弧新增到當前子路徑。

語法

js
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle)
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise)

ellipse() 方法建立一個以 (x, y) 為中心,具有 radiusXradiusY 半徑的橢圓弧。路徑從 startAngle 開始,到 endAngle 結束,並沿 counterclockwise 指定的方向(預設為順時針)繪製。

引數

x

橢圓中心的 X 軸(水平)座標。

y

橢圓中心的 Y 軸(垂直)座標。

radiusX

橢圓的主軸半徑。必須是非負數。

radiusY

橢圓的短軸半徑。必須是非負數。

rotation

橢圓的旋轉角度,以弧度表示。

startAngle

橢圓開始處的偏心角,從正 X 軸順時針測量,並以弧度表示。

endAngle

橢圓結束處的偏心角,從正 X 軸順時針測量,並以弧度表示。

counterclockwise 可選

一個可選的布林值,如果為 true,則逆時針(anticlockwise)繪製橢圓。預設值為 false(順時針)。

返回值

無(undefined)。

示例

繪製一個完整的橢圓

此示例在 π/4 弧度(45°)的角度繪製了一個橢圓。要繪製一個完整的橢圓,弧從 0 弧度(0°)開始,到 2π 弧度(360°)結束。

HTML

html
<canvas id="canvas" width="200" height="200"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Draw the ellipse
ctx.beginPath();
ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI);
ctx.stroke();

// Draw the ellipse's line of reflection
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(0, 200);
ctx.lineTo(200, 0);
ctx.stroke();

結果

各種橢圓弧

此示例建立了三個具有不同屬性的橢圓路徑。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "red";
ctx.beginPath();
ctx.ellipse(60, 75, 50, 30, Math.PI * 0.25, 0, Math.PI * 1.5);
ctx.fill();

ctx.fillStyle = "blue";
ctx.beginPath();
ctx.ellipse(150, 75, 50, 30, Math.PI * 0.25, 0, Math.PI);
ctx.fill();

ctx.fillStyle = "green";
ctx.beginPath();
ctx.ellipse(240, 75, 50, 30, Math.PI * 0.25, 0, Math.PI, true);
ctx.fill();

結果

規範

規範
HTML
# dom-context-2d-ellipse-dev

瀏覽器相容性

另見