1. 程式人生 > >canvas之文字換行

canvas之文字換行

當canvas的寬度不夠寬時,canvas不會自動換行,可以用下面的程式碼處理

<body>
    <canvas id="canvas" width="200" height="200" style="background:pink;"></canvas>
    <script>
    function draw() {
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var str = "當內容特別多的時候,canvas不會自動換行,需要特別處理當內容特別多的時候,canvas不會自動換行,需要特別處理當內容特別多的時候,canvas不會自動換行,需要特別處理當內容特別多的時候,canvas不會自動換行,需要特別處理";
        var canvasWidth = ctx.canvas.width;
        ctx.font = "20px Microsoft";
        console.log(ctx.measureText(str))
        canvas.height = Math.ceil(ctx.measureText(str).width / canvasWidth) * 25;
        ctx.font = "16px Microsoft"; //重新定義畫布的高度後,需要重新定義字型的大小,否則變成預設值
        var initHeight = 25; //繪製字型距離canvas頂部初始的高度
        var lastSunStrIndex = 0; //每次開始擷取的字串的索引
        var contentWidth = 0;

        if (ctx.measureText(str).width <= canvasWidth) {
            ctx.fillText(str, 0, initHeight);
            return
        }

        for (let i = 0; i < str.length; i++) {
            contentWidth += ctx.measureText(str[i]).width;
            if (contentWidth > canvasWidth - 32) {
                ctx.fillText(str.substring(lastSunStrIndex, i), 12, initHeight) //繪製未擷取的部分
                initHeight += 25;
                contentWidth = 0;
                lastSunStrIndex = i;
            }
            if (i == str.length - 1) {
                ctx.fillText(str.substring(lastSunStrIndex, i + 1), 12, initHeight);
            }

        }
    }
    draw()
    </script>
</body>

關於canvas 繪製文字的方法與樣式設定

canvas 提供了兩種方法來渲染文字:

fillText(text, x, y [, maxWidth])

在指定的(x,y)位置填充指定的文字,繪製的最大寬度是可選的.

strokeText(text, x, y [, maxWidth])

在指定的(x,y)位置繪製文字邊框,繪製的最大寬度是可選的.

設定樣式

font = value

當前我們用來繪製文字的樣式. 這個字串使用和 CSS font 屬性相同的語法. 預設的字型是 10px sans-serif

textAlign = value

文字對齊選項. 可選的值包括:startendleftright or center. 預設值是 start

textBaseline = value

基線對齊選項. 可選的值包括:tophangingmiddlealphabeticideographicbottom。預設值是 alphabetic。

direction = value

文字方向。可能的值包括:ltrrtl

inherit。預設值是 inherit。