Draw centered text in Canvas

There are two ways to draw text in canvas: fillText() and strokeText(), one is filled text and the other is stroked text. Below is the padding text used.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fillText方法</title>
</head>
<body>
    <canvas id="canvas" width="200" height="150" style="border: 1px dashed gray;display: block"></canvas>
    <script>
        window.onload = function () {
            var c = document.getElementById("canvas");
            var cxt = c.getContext('2d');
            var text = "填充文本";
            cxt.font = "30px 微软雅黑";

            var textWidth = cxt.measureText(text).width;
            var canvasWidth = c.width;
            var xPosition = canvasWidth / 2 - textWidth / 2;

            cxt.fillText(text,xPosition,50);
        };
    </script>
</body>
</html>

cxt.measureText(text).width is used to obtain the width of the text. cxt.font="30px Microsoft Yahei" must be placed in front of it, that is, the font size must be set first, and then measure its value.

The coordinates of drawing text in the canvas are based on the coordinates of its lower left corner.

Guess you like

Origin blog.csdn.net/wudechun/article/details/127614826