Metoda getContext

Metoda getContext ustawia kontekst do rysowania przed pracą z canvas. W pierwszym parametrze metody podajemy typ kontekstu - '2d' lub '3d', a w drugim - jego atrybuty.

Składnia

javascriptcanvas.getContext(typ kontekstu, atrybuty);

Przykład

Stwórzmy canvas getContext i ustawmy mu przezroczyste tło za pomocą atrybutu alpha, informującego przeglądarkę o obecności kanału alfa:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptconst canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {alpha: true});

ctx.rect(50, 50, 100, 100);
ctx.fillStyle = 'red';
ctx.fill();

Результат:

Przykład

A teraz stwórzmy nieprzezroczyste tło:

html<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
javascriptconst canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {alpha: false});

ctx.rect(50, 50, 100, 100);
ctx.fillStyle = 'red';
ctx.fill();

Результат: