1

目标:设置行高为文字高度的1.5倍,实现文字垂直居中
结果:只设置 textBaselinetopmiddle都不能成功

先看下只设置为 top 的效果

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1920" height="1080" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

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

</script>

</body>
</html>

效果

image.png

并不是从顶格线开始的。

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

修改:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1920" height="1080" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

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


</script>

</body>
</html>

结果对比:

image.png


zeroyl
156 声望2 粉丝