I am currently working on drawing text to an HTML canvas element and positioning an HTML button next to it using CSS styling and JavaScript. My goal is to have both the text and button share the same font and baseline alignment, but I am facing some challenges given my constraints.
- By default, the canvas-drawn text uses
textBaseline = 'alphabetic'
, which cannot be changed for compatibility reasons. On the other hand, absolute positioning of the HTML element uses top or bottom margin, not baseline alignment. - The
TextMetrics
documentation on MDN mentions various vertical measurements that are only available in Chrome after specific flags have been set. I need a solution that works on a majority of current browsers. - Since I do not know the font being used, hard-coding metric information about the font is not feasible.
Given these challenges, what are my options?
Should I render the font to a second off-screen canvas and analyze its pixel data to determine its actual dimensions? Can I rely on these dimensions to match those used in computing the size of the button, especially for more decorative fonts?
Is there a need to use a spacer image? The key difference between my question and that one lies in the fact that I am handling positioning in JavaScript, allowing me to utilize the assistance of a canvas.
Can the
vertical-align
CSS property be leveraged without a spacer image by creating an outer box with a defined baseline and nesting the button inside aligned to the same baseline?Are there any other alternatives I could explore?