canvas fillText文字如何换行?
发布于 6 年前 作者 mhu 11193 次浏览 来自 问答

如何写

5 回复

把你的  that.data.address 放在一个view里面,如果太长 view 会换行,height会被撑高,这样就知道有没有换行了

这样考虑的目的 是  0-9,a-z 的长度 与 纯中文长度不同,

如果就只是放一下地址,  你直接就根据 一行能放最多的中文截取一下length好了

<view
    class="exhibition-name canvas-draw"
    data-size="18"
    data-weight="1"
    data-color="{{invitation.skinColorSeries ? '#ffffff' : '#475669'}}"
    data-content="{{invitation.expoName}}"
    style="color: {{invitation.skinColorSeries ? '#ffffff' : '#475669'}};">
    {{invitation.expoName}}
</view>

我是根据容器与行高进行判断的(追求一下,行高进行rpx比例还原)

// 写字
        function fontDraw(nodeInfo) {
 
            let fontSize = Math.floor(Number(nodeInfo.dataset.size) * scaleVal)
            let fontColor = nodeInfo.dataset.color || '#475669'
 
            ctx.setFontSize(fontSize)
            ctx.setFillStyle(fontColor)
            ctx.setTextAlign('center')
            ctx.setTextBaseline('top')
 
            // 处理换行 依据是高度大于两倍字体
            let lineCount = Math.floor(nodeInfo.height / fontSize)
 
            if (lineCount === 1) {
                 
                ctx.fillText(nodeInfo.dataset.content, that.data.contentWidth / 2, nodeInfo.top)
                // 如果要加粗
                if (nodeInfo.dataset.weight) {
                    ctx.fillText(nodeInfo.dataset.content, that.data.contentWidth / 2 + .2, nodeInfo.top + .2)
                    ctx.fillText(nodeInfo.dataset.content, that.data.contentWidth / 2 - .2, nodeInfo.top - .2)
                }
            } else {
 
                let contentWord = nodeInfo.dataset.content
                let lineNum = Math.floor(contentWord.length / lineCount)
                 
                for (let i = 0; i < lineCount; i++) {
                     
                    let tempWord = i === lineCount - 1 ? contentWord.substr(i * lineNum) : contentWord.substr(i * lineNum, lineNum)
                    let tempTop = nodeInfo.top + ((fontSize + 5) * i)
 
                    ctx.fillText(tempWord, that.data.contentWidth / 2, tempTop)
                     
                    // 如果要加粗
                    if (nodeInfo.dataset.weight) {
                        ctx.fillText(tempWord, that.data.contentWidth / 2 + .2, tempTop + .2)
                        ctx.fillText(tempWord, that.data.contentWidth / 2 - .2, tempTop - .2)
                    }
                     
                }
            }
        }

我的是这样的,动态的,看你的还不是很明白。

请解释一下,我没看明白,谢谢

回到顶部