javascript - 调用Canvas Rendering Context2D.fill Text时Y坐标定义了什么?

标签 javascript html html5-canvas

我正在查看 this page on MDN .

在语法部分它说:

y ... The y-axis coordinate of the point at which to begin drawing the text, in pixels.

我从页面复制了他们的示例并将 y 设置为 0:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.font = '50px serif';
ctx.fillText('Hello world', 0, 0);
<canvas id="canvas" width="400" height="150" style="border: 1px solid black"></canvas>

正如您在运行该代码片段时所见, Canvas 上看不到任何内容。所以 x 确实定义了左坐标,但是 y 没有定义绘制文本的顶部坐标。 y 定义了什么?是基线吗?

最佳答案

在坐标 (0,0) 处, Canvas 使用字母 i 的默认基线绘制文本。 e 上面绘制字符的线。

基线的位置可以根据 MDN 由以下属性控制:

MDN baseline settings

具有基线挂起的预期结果的示例工作代码:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.textBaseline = 'hanging';
ctx.font = '50px serif';
ctx.fillText('Hello world', 0, 0);
<canvas id="canvas" width="400" height="150" style="border: 1px solid black"></canvas>

代码笔: https://codepen.io/nagasai/pen/abbNJVr

关于javascript - 调用Canvas Rendering Context2D.fill Text时Y坐标定义了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646876/

相关文章:

Javascript - 过滤对象中的数组

javascript - CSS如何使用Auto设置margin-top

html - 如何在标签旁边放置单选按钮

javascript - 使用百分比而不是像素会更改 html 5 Canvas 会更改其属性吗?

javascript - globalcompositeoperation=source-over 是否与 putimagedata 一起使用?

javascript - 检查父 div 是否有高度

javascript - 我正在尝试将列添加到谷歌时间线图表

html - 如何制作像 Google Doodle 的神秘博士这样的 HTML5 游戏?

javascript - ajax自动完成问题

javascript - 如何使用php读取html中标签的id?