CanvasRenderingContext2D: createPattern() 方法

Baseline 已廣泛支援

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

Canvas 2D API 的 CanvasRenderingContext2D.createPattern() 方法使用指定的影像和重複方式建立圖案。此方法返回一個 CanvasPattern 物件。

此方法不會直接在畫布上繪製任何內容。它建立的圖案必須賦給 CanvasRenderingContext2D.fillStyleCanvasRenderingContext2D.strokeStyle 屬性,之後才能應用於任何後續繪圖。

語法

js
createPattern(image, repetition)

引數

圖片

用作圖案影像的影像。它可以是以下任何一種:

重複方式

一個字串,指示如何重複圖案的影像。可能的值包括:

  • "repeat"(兩個方向重複)
  • "repeat-x"(僅水平方向重複)
  • "repeat-y"(僅垂直方向重複)
  • "no-repeat"(兩個方向都不重複)

null 值被視為與空字串("")相同:兩者都是 "repeat" 的同義詞。

返回值

CanvasPattern

一個描述圖案的不透明物件。

如果 image 未完全載入(HTMLImageElement.completefalse),則返回 null

示例

從影像建立圖案

此示例使用 createPattern() 方法建立具有重複源影像的 CanvasPattern。建立後,該圖案將被賦給畫布上下文的填充樣式,並應用於一個矩形。

原始影像如下所示:

A flowery pattern

HTML

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

JavaScript

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

const img = new Image();
img.src = "canvas_create_pattern.png";
// Only use the image after it's loaded
img.onload = () => {
  const pattern = ctx.createPattern(img, "repeat");
  ctx.fillStyle = pattern;
  ctx.fillRect(0, 0, 300, 300);
};

從畫布建立圖案

在此示例中,我們從一個離屏畫布的內容建立圖案。然後,我們將該圖案應用於主畫布的填充樣式,並用圖案填充該畫布。

JavaScript

js
// Create a pattern, offscreen
const patternCanvas = document.createElement("canvas");
const patternContext = patternCanvas.getContext("2d");

// Give the pattern a width and height of 50
patternCanvas.width = 50;
patternCanvas.height = 50;

// Give the pattern a background color and draw an arc
patternContext.fillStyle = "#ffeecc";
patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
patternContext.arc(0, 0, 50, 0, 0.5 * Math.PI);
patternContext.stroke();

// Create our primary canvas and fill it with the pattern
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const pattern = ctx.createPattern(patternCanvas, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Add our primary canvas to the webpage
document.body.appendChild(canvas);

結果

規範

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

瀏覽器相容性

另見