Search code examples
javascripthtmlcanvasletter-spacing

Is it possible to somehow get a html element as an image to render on a canvas?


It may seem like a really random question, but I am trying to figure out a hack to get correctly letter-spaced text rendered on a canvas.

After much searching in google it seems like there is no way to really do this. The first thing I tried was rendering each character in a string, measuring it, adding it to an offset, adding the letter-spacing, but the results are pretty poor. Probably due to information contained in the font file about character pairing spaces etc.

The only thing I can think of to get a perfect result is to render text to a html element, set letter spacing via CSS, then somehow capture the element in memory as an image. I know it is unlikely but does anyone know a way to do this?


Solution

  • Why not just move the HTML element on top of the canvas?

    <canvas style="background-color:cyan; left:100px; right:100px; width:100px; height:100px; position:absolute" >
    </canvas>
    <p style="left:120px; right:100px; position:absolute; z-index:100; ">this is a test</p>