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

浏览器兼容性

另见