微信小程序跳

时间:2025-04-13 07:10:19

/**

     * 画布文本换行绘制

     * canvasContext 画布实例

     * text 要写入的文本

     * x 初始x轴位置

     * y 初始y轴位置

     * ySpacing 换行后,每行直接的间隔

     * maxWidth 此文本写入画布的最大宽度,超过此宽度就换行

     * color 文本颜色

     * size 文本字体大小

     * align 文本方向 left rigt center 额一直搞不清楚这个方向是怎么个原理

     * @returns { textY 绘制最后一行文本的Y轴结束坐标,drawNum 画布本次绘制了几次 }

     */

    canvasTextNewlinedraw (options) {

        const { canvasContext, text = '', x = 0, y = 0, ySpacing = 0, maxWidth = 0, color, size, align } = options

        return new Promise((resolve, reject) => {

            size && canvasContext.setFontSize(size)

            align && canvasContext.setTextAlign(align)

            color && canvasContext.setFillStyle(color)

            const textList = text.split('')

            let currText = '', textY = 0, drawNum = 0

            for (let i = 0; i < textList.length; i++) {

                if (canvasContext.measureText(currText + textList[i]).width + x > maxWidth - 10) {

                    textY += textY === 0 ? y : ySpacing

                    canvasContext.fillText(currText, x, textY)

                    currText = textList[i]

                    drawNum++

                } else {

                    currText += textList[i]

                }

            }

            textY = textY === 0 ? y : textY + ySpacing

            canvasContext.fillText(currText, x, textY)

            drawNum++

            canvasContext.draw(true, _ => {

                setTimeout(() => {

                    resolve({ y: textY, res: _, drawNum })

                }, 100)

            })

        })

    }