Thuộc tính textBaseline

Thuộc tính textBaseline thiết lập căn chỉnh theo chiều dọc cho văn bản được vẽ bằng phương thức fillText hoặc phương thức strokeText. Nhận một trong các giá trị có thể: top, hanging, middle, alphabetic (mặc định), ideographic, bottom (để hiểu các giá trị xem www.w3schools.com/tags/canvas_textbaseline.asp).

Cú pháp

javascriptngữ cảnh.textBaseline = giá trị;

Ví dụ

Hãy thiết lập căn chỉnh dọc theo đường trên cùng cho văn bản:

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

Результат:

Ví dụ

Và bây giờ hãy thiết lập căn chỉnh dọc theo đường dưới cùng cho văn bản:

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

Результат:

Xem thêm

  • thuộc tính textAlign,
    căn chỉnh văn bản theo chiều ngang
  • thuộc tính font,
    thiết lập kích thước và kiểu phông chữ