I am creating some images using the canvas. I would like to be able to draw text in given rect (i.e. offset x, offset y, width and height) on a canvas and that text to be as large as possible without overflowing and if possible, with word wrapping. Is it possible?
Share
It’s possible.
no-wrapping:
You can use
CanvasRenderingContext2D.measureText()method, which accepts a string, and returns a object { width: float }. You have to find out the height by doing some math using font’s size. Then just enumerate the font sizes in a binary search way. soon you will find the best size for the canvas.wrapping:
You have to find out the wrapping point in the string and calculate their width and height you self.
but there is a better easier way to do this.
create a hidden(visibility: hidden not display: none) div, defines its width, and put your text inside. enumerates font’s size, and check if it overflows or grows too high.