วิธีการ getContext
วิธีการ getContext กำหนดบริบทสำหรับ
การวาดภาพก่อนทำงานกับ canvas ในพารามิเตอร์แรก
ของวิธีการเราระบุประเภทของบริบท - '2d' หรือ '3d',
และในพารามิเตอร์ที่สอง - แอตทริบิวต์ของบริบทนั้น
ไวยากรณ์
canvas.getContext(ประเภทบริบท, แอตทริบิวต์);
ตัวอย่าง
มาสร้าง canvas ด้วย 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();
: