CanvasRenderingContext2D: fill()-Methode

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Die CanvasRenderingContext2D.fill() Methode der Canvas 2D API füllt den aktuellen oder angegebenen Pfad mit dem aktuellen fillStyle.

Syntax

js
fill()
fill(path)
fill(fillRule)
fill(path, fillRule)

Parameter

fillRule

Der Algorithmus, durch den bestimmt wird, ob ein Punkt innerhalb oder außerhalb des Füllbereichs liegt. Mögliche Werte:

nonzero

Die Non-Zero-Wickelregel. Standardregel.

evenodd

Die Even-Odd-Wickelregel.

path

Ein Path2D-Pfad, der gefüllt werden soll.

Rückgabewert

Keiner (undefined).

Beispiele

Ein Rechteck füllen

Dieses Beispiel füllt ein Rechteck mit der fill()-Methode.

HTML

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

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.rect(10, 10, 150, 100);
ctx.fill();

Ergebnis

Ein Pfad und eine fillRule angeben

Dieses Beispiel speichert einige sich schneidende Linien in einem Path2D-Objekt. Die fill()-Methode wird dann verwendet, um das Objekt auf der Leinwand darzustellen. Ein Loch wird in der Mitte des Objekts unbefüllt gelassen, indem die Regel "evenodd" verwendet wird; standardmäßig (mit der Regel "nonzero") würde das Loch ebenfalls gefüllt.

HTML

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

JavaScript

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

// Create path
let region = new Path2D();
region.moveTo(30, 90);
region.lineTo(110, 20);
region.lineTo(240, 130);
region.lineTo(60, 130);
region.lineTo(190, 20);
region.lineTo(270, 90);
region.closePath();

// Fill path
ctx.fillStyle = "green";
ctx.fill(region, "evenodd");

Ergebnis

Spezifikationen

Specification
HTML
# dom-context-2d-fill-dev

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
fill
path parameter

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Siehe auch