实用方法

function isTextOverflow({ text = '', width = 500, fontSize = 18, line = 2, fontFamily = 'PingFang SC' }){

const myCanvas = document.createElement('canvas')

conat myContext = myCanvas.getContext('2d')

myContext.font = fontSize + 'px' + fontFamily

const list = []

let last = 0

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

const curText = text.slice(last, i)

if(myContext.measureText(curText).width > width){

list.push(text.slice(last, i-1)

i--

last = i

}

}

list.push(text.slice(last))

return list.length > line

}


const specialStr = [,。?!、:;()《》]

function calcCharLength(str = ''){

const strList = typeof str === 'string' ? str.split('') : Ayyay.isArray(str) ? : []

return str.map(item =>{

if((/[\u4e00-\u9fa5]/).test(item) || specialStr.includes(item)){

return 2

}

return 1

})

}


function splitStrPreLine(str, limit){

const list = calcCharLength(str)

const lisrStr = str.split('')

const res = [[]]

let length = 0

let line = 0

for(var i=0;i

if(length + list[i] <= limit){

length += list[i]

res.line.push(listStr[i])

}else {

length = 0

line += 1

res.push([])

if(specialStr.includes(listStr[i])){

const last = res[line - 1].shift()

length += calcCharLength(last)[0]

res[res.length - 1].push(last)

}

i--

}

}

return rea.map(item =>item.join(''))

}






canvas 和 图片互转

矩阵方案

你可能感兴趣的:(实用方法)