CanvasRenderingContext2D: clip() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.clip() 方法會將當前或指定的路徑轉換為當前的剪下區域。如果之前存在剪下區域,則會與當前或指定的路徑相交,從而建立新的剪下區域。

在下圖所示的影像中,紅色輪廓代表一個星形剪下區域。只有網格圖案中位於剪下區域內的部分會被繪製出來。

Star-shaped clipping region

注意: 請注意,剪下區域僅由新增到路徑中的形狀構成。它不適用於直接繪製到畫布上的形狀圖元,例如 fillRect()。您需要先使用 rect() 將矩形形狀新增到路徑中,然後才能呼叫 clip()

注意: 剪下路徑不能直接恢復。您必須在使用 clip() 呼叫之前使用 save() 儲存您的畫布狀態,並在使用 restore() 完成在剪下區域內的繪圖後恢復它。

語法

js
clip()
clip(path)
clip(fillRule)
clip(path, fillRule)

引數

fillRule

確定一個點是位於剪下區域內部還是外部的演算法。可能的值

nonzero

非零環繞規則。預設規則。

evenodd

奇偶纏繞規則

路徑

一個 Path2D 路徑,用作剪下區域。

返回值

無(undefined)。

示例

一個簡單的剪下區域

此示例使用 clip() 方法根據圓形弧線的形狀建立剪下區域。然後繪製兩個矩形;只有位於剪下區域內的部分會被渲染。

HTML

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

JavaScript

剪下區域是一個完整的圓形,其中心位於 (100, 75),半徑為 50。

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

// Create circular clipping region
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.clip();

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "orange";
ctx.fillRect(0, 0, 100, 100);

結果

指定路徑和 fillRule

此示例將兩個矩形儲存到 Path2D 物件中,然後使用 clip() 方法將其設定為當前的剪下區域。"evenodd" 規則會在剪下矩形相交處建立一個孔;預設情況下(使用 "nonzero" 規則),不會有孔。

HTML

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

JavaScript

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

// Create clipping path
let region = new Path2D();
region.rect(80, 10, 20, 130);
region.rect(40, 50, 100, 50);
ctx.clip(region, "evenodd");

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

結果

建立一個複雜的剪下區域

此示例使用兩個路徑(一個矩形和一個正方形)來建立複雜的剪下區域。呼叫兩次 clip() 方法,首先使用 Path2D 物件將當前剪下區域設定為圓形,然後再次將圓形剪下區域與正方形相交。最終的剪下區域是表示圓形和正方形交集的形狀。

HTML

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

JavaScript

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

// Create two clipping paths
let circlePath = new Path2D();
circlePath.arc(150, 75, 75, 0, 2 * Math.PI);
let squarePath = new Path2D();
squarePath.rect(85, 10, 130, 130);

// Set the clip to the circle
ctx.clip(circlePath);
// Set the clip to be the intersection of the circle and the square
ctx.clip(squarePath);

// Draw stuff that gets clipped
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

結果

規範

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

瀏覽器相容性

另見