Daniel
Daniel

Reputation: 3514

Text paragraph with fixed ratio within svg

I generate dynamic SVG graphics on the fly using JavaScript. For this purpose a paragraph of text should be added into a box with a fixed aspect ratio inside the svg image. The text length may differ between short and also very long text length. As the actual font size is not important for my purpose I use the viewBox attribute to show the whole paragraph within the box. As far as I researched and tested until now, svg does not provide any automatic line breaking functionality, therefore I might use a standard HTML div within a foreignObject to make use of HTML line breaking.

Are there any possibilities to get a div with fixed aspect ratio based on its content length? I already managed to get such a div by an ittertive decreasing of width until the ratio more or less fits the purpose. But this solution is rather imprecise and needs to add the div to the DOM before actually inserting it into the svg. Are there any CSS solutions?

Upvotes: 0

Views: 194

Answers (1)

Daniel
Daniel

Reputation: 3514

As unfortunately nobody could help to solve this problem, I implemented the following (more or less working) solution:

for(var i = 0; i < 200; i++){
    if($('#wrapper').width()/$('#wrapper').height() <= 5){
        console.log($('#wrapper').width()/$('#wrapper').height())
        break;
    }
    $('#wrapper').width($('#wrapper').width()*0.8);
}

for(var y = 0; y < 200; y++){
    if($('#wrapper').width()/$('#wrapper').height() >= 4.9){
        break;
    }
    $('#wrapper').width($('#wrapper').width()*1.02);
}

This approach tries to itteratively converge the aspect ratio towards an approximately correct ratio.

This is by far not an optimal solution, but at least a working one.

Upvotes: 0

Related Questions