当前位置: 首页 > 工具软件 > CanvasText > 使用案例 >

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

皇甫福
2023-12-01
<!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>

 

 类似资料: