html5图片怎么顶格,html5 canvas textBaseline 之坑

本文探讨了在HTML5 Canvas中如何实现文字垂直居中,通过示例代码展示了仅设置`textBaseline`为`top`或`middle`无法达到预期效果的问题,并提供了利用`actualBoundingBoxAscent`属性来精确调整文字垂直位置的方法,确保文字能够正确地在设定的行高中垂直居中显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标:设置行高为文字高度的1.5倍,实现文字垂直居中

结果:只设置 textBaseline 为 top 和 middle都不能成功

先看下只设置为 top 的效果

Your browser does not support the HTML5 canvas tag.

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

//Draw a red line at y=100

ctx.strokeStyle="blue";

ctx.moveTo(5,100);

ctx.lineTo(1920,100);

ctx.stroke();

ctx.font="200px Arial"

//Place each word at y=100 with different textBaseline values

ctx.textBaseline="top";

ctx.fillText("审讯室",5,100);

效果

bVbGW6k

并不是从顶格线开始的。

设置为 middle 时也是中线上面部分的高度比下面的高度大。

修改:

Your browser does not support the HTML5 canvas tag.

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

//Draw a red line at y=100

ctx.strokeStyle="blue";

ctx.moveTo(5,100);

ctx.lineTo(1920,100);

ctx.stroke();

ctx.font="200px Arial"

//Place each word at y=100 with different textBaseline values

ctx.textBaseline="top";

ctx.fillText("审讯",5,100);

var textMetrics = ctx.measureText("审讯室");

var actualBoundingBoxAscent = textMetrics.actualBoundingBoxAscent;

ctx.fillText("审讯",500,100+actualBoundingBoxAscent);

结果对比:

bVbGXhG

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值