Last active
June 18, 2018 21:21
-
-
Save neopunisher/ea5edd16cc3c5f7b28bbf510a7445898 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function lines(elem, limit = 3, delimiter = ' '){ | |
const width = elem.clientWidth | |
const words = elem.innerText.split(delimiter) | |
const ctx = document.createElement('canvas').getContext('2d'), | |
fnt = window.getComputedStyle(elem).getPropertyValue('font') | |
ctx.font = fnt | |
console.log('font:', fnt) | |
const measure = (start, end)=>ctx.measureText(words.slice(start, end).join(delimiter)).width | |
var lens = {}, j = 0, line = 1; | |
for (var i = 0; i < words.length; i++) { | |
if(measure(j, i) > width){ | |
// lens[line] = {width: measure(j, i - 1), text: words.slice(j, i - 1).join(delimiter), j:j, i:i-1} | |
if(line > limit){ | |
// console.log({words: words, len: words.length, width: width, lines: line, lens: lens}) | |
return words.slice(0, j).join(' ') | |
} | |
j = i - 1; | |
line++; | |
} | |
} | |
//lens[line] = {width: measure(j, i - 1), text: words.slice(j, i - 1).join(' '), j:j, i:i-1} | |
//console.log({words: words, len: words.length, width: width, lines: line, lens: lens}) | |
return words.join(delimiter) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment