Metóda getContext

Metóda getContext nastavuje kontext pre kreslenie pred prácou s canvas. V prvom parametri metódy uvádzame typ kontextu - '2d' alebo '3d', a v druhom - jeho atribúty.

Syntax

javascriptcanvas.getContext(typ kontextu, atribúty);

Príklad

Vytvorme canvas getContext a nastavme mu priehľadné pozadie cez atribút alpha, ktorý ukazuje prehliadaču prítomnosť alfa kanála:

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();

Результат:

Príklad

A teraz vytvorme nepriehľadné pozadie:

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();

Результат: