Skip to content

How to render an image with dynamic size #99

Answered by Trugamr
ReiKohaku asked this question in Q&A
Discussion options

You must be logged in to vote

Text can be measured before drawing which gives you the height that text would take after it's drawn.

This function takes array of lines which is returned by using measureText() which can be used to calculate height of the text.

function getTextHeight(lines: TextMetricsLine[]) {
  const last = lines[lines.length - 1]
  return last.y + last.height
}

Example

const canvas = new Canvas(600, 0)
const context = canvas.getContext('2d')

const text = 'what do you call a dog that can do magic tricks? a labracadabrador 🐶✨'

// Measure text size
context.font = `bold 48px poppins`
context.textWrap = true
context.textBaseline = 'top'
const metrics = context.measureText(text, canvas.width)
const height = 

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by samizdatco
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #90 on June 02, 2022 18:44.