fitting text into the box

前端 未结 2 625
长发绾君心
长发绾君心 2021-02-09 07:24

on my website i allow users to create pictures with line of text they specify drawn on the picture

currently i use for that imagemagick convert - i specify svg template

2条回答
  •  梦如初夏
    2021-02-09 08:04

    You could add a script within the SVG template which called when the SVG is loaded and uses getComputedTextLength() to resize the font. It's a bit of a hacky solution, but it seems to work.

    Here's a quick example that draws a box and some text inside it. The text should be resized to always fit in the box no matter how long it is (up to point at least):

    To call the code when the SVG is loaded include onload="int(evt)" in the SVG tag.

     
     
     
    

    Then the actual script:

      
    

    I just used a for loop to decrement the font-size until the text length is less than the maximum specified; I'm sure there's a better way to resize the text.

    Finally the actual text and box:

    
    
     whatever text
    
    
    

    If you change the text, the font-size should change so that it fits inside the box. You'll probably want to change the x- and y- values to correctly centre the text too.

提交回复
热议问题