คุณสมบัติ textBaseline

คุณสมบัติ textBaseline กำหนดการจัดตำแหน่งแนวตั้ง ของข้อความที่วาดด้วยวิธี fillText หรือวิธี strokeText รับค่าที่เป็นไปได้หนึ่งใน: top, hanging, middle, alphabetic (ค่าเริ่มต้น), ideographic, bottom (เพื่อให้เข้าใจค่าต่างๆ ดูที่ www.w3schools.com/tags/canvas_textbaseline.asp)

ไวยากรณ์

javascriptcontext.textBaseline = value;

ตัวอย่าง

มากำหนดการจัดตำแหน่งแนวตั้งให้กับข้อความ ตามเส้นบนสุด:

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

ctx.strokeStyle = 'red';
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.font="14px Arial";
ctx.textBaseline = 'top'; 
ctx.fillText('text', 80, 100);

Результат:

ตัวอย่าง

และตอนนี้มากำหนดการจัดตำแหน่งแนวตั้งให้กับข้อความ ตามเส้นล่างสุด:

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

ctx.strokeStyle = 'red';
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.stroke();
ctx.font="14px Arial";
ctx.textBaseline="bottom"; 
ctx.fillText('text', 80, 100); 

Результат:

ดูเพิ่มเติม

  • คุณสมบัติ textAlign,
    ซึ่งจัดตำแหน่งข้อความในแนวนอน
  • คุณสมบัติ font,
    ซึ่งกำหนดขนาดและประเภทของตัวอักษร