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
canvas.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:
<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
const 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:
<canvas id="canvas" width="200" height="200" style="background: #f4f4f4;"></canvas>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d', {alpha: false});
ctx.rect(50, 50, 100, 100);
ctx.fillStyle = 'red';
ctx.fill();
: