canvas文本属性-textBaseline-垂直对齐

本文深入探讨了canvas的textBaseline属性,详细解释了不同垂直对齐方式的含义,并通过实例展示了如何调整文本在canvas上的垂直位置,帮助开发者更好地控制文本绘制效果。

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>canvas文本属性textBaseline</title>
    <style>
        body{margin: 0;overflow: hidden}
        #test{background: antiquewhite;}
    </style>
</head>
<body>
    <canvas id="test"></canvas>
    <script>
        const cvs=document.getElementById('test');
        cvs.width=window.innerWidth;
        cvs.height=window.innerHeight;
        const ctx=cvs.getContext('2d');
    
        /*辅助线*/
        ctx.strokeStyle='#999';
        ctx.setLineDash([8]);
        ctx.moveTo(30,300);
        ctx.lineTo(700,300);
        ctx.stroke();
    
        /*font 设置字号字体*/
        ctx.font="24px Arial";
    
    
    
        /*
        * textBaseline 文字垂直对齐方式
        *   top:上对其
        *   middle:垂直居中对齐
        *   bottom:下对齐
        *   hanging:悬挂基线对齐
        *   alphabetic:标准字母基线对齐,默认
        *   ideographic:表意文字基线
        * */
        ctx.textBaseline='top';
        ctx.fillText('top',100,300);
    
        ctx.textBaseline='middle';
        ctx.fillText('middle',200,300);
    
        ctx.textBaseline='bottom';
        ctx.fillText('bottom',300,300);

        ctx.textBaseline='hanging';
        ctx.fillText('hanging',400,300);
    
        ctx.textBaseline='alphabetic';
        ctx.fillText('alphabetic',500,300);
            
        ctx.textBaseline='ideographic';
        ctx.fillText('ideographic',650,300);
    
    </script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值