getContextメソッド
メソッドgetContextは、キャンバスを操作する前に
描画コンテキストを設定します。メソッドの最初のパラメータで
コンテキストのタイプ - '2d'または'3d'を指定し、
2番目でその属性を指定します。
構文
canvas.getContext(コンテキストタイプ, 属性);
例
キャンバスのgetContextを作成し、
属性alphaを通して透明な背景を設定しましょう。
これはブラウザにアルファチャンネルの存在を示します:
<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();
:
例
次に、不透明な背景を作成してみましょう:
<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();
: