Maximum font size of text on canvas js

Viewed 150

The task: We have the width and the height of the canvas. We have the font family and line-height.

Question: What is the maximal possible font size for some random text of any length?

Here is some helping functions that help to measure the height of wrapped text on the canvas:

function calculateTextLines(context, maxWidth, lineHeight) {
    minimum_text_width = 0
    let words = text.split(' ')
    let line = ''
    let lines = []

    // # Generates an array of wrapped line and
    // # calculates the height of future text to center it later
    for (let n = 0; n < words.length; n++) {
        // # The next 3 lines calculates minimum possible width of the text box
        let minimum_text_width_metrics = context.measureText(words[n])
        if (minimum_text_width_metrics.width > minimum_text_width)
            minimum_text_width = minimum_text_width_metrics.width

        let testLine = line + words[n] + ' '
        let metrics = context.measureText(testLine)
        let testWidth = metrics.width
        if (testWidth > maxWidth && n > 0) {
            lines.push(line)
            line = words[n] + ' '
        } else {
            line = testLine
        }
    }
    lines.push(line)

    if (minimum_text_width > canvas.width)
        minimum_text_width = canvas.width

    return lines
}


function calculateNewHeight(new_width, fontsize) {
    let ctx = canvas.getContext('2d')
    ctx.save()

    ctx.font = fontsize + 'px ' + font.family
    ctx.textAlign = font.align
    const lines = calculateTextLines(ctx, new_width, font.line - height * fontsize)

    ctx.restore()
    return lines.length * (font.line - height * fontsize)
}
0 Answers
Related