I am using Raphael.js to create polygons, (or actually closed paths) over an image. I want to put text inside the polygons. Is there any way to create a text element and then adjust its size and position so that the whole thing will be within the bounds of a polygon?
Are there at least any algorithms that can give me good guesses that I could manually adjust?
Okay, I gave this some thought over the course of the day, and finally had the chance to throw together a little demo code. It is glaringly imperfect in many ways but may form a good starting place, and does seem to work well with most of my randomly generated polygons.
Part 1: Centering the text over the polygon. Using the bounding box proved wildly unsatisfactory, so instead of I devised a technique to average all of the points in a given path
container:Part 2: Collision detection. I needed a mechanism to check if a given object is inside the current shape. Being lazy, I simply extended the Raphael element object prior to creating my canvas.
Part 3: Iterative sizing. Basically, we use the coordinates produced above and apply them to the generated label text. We reduce the scale once each iteration until we go beneath a certain threshold, at which point MY code simply gives up (yours probably shouldn’t):
And the result looks well for most of the purely random polygons I threw at it. I’m sure it’s far more computationally intensive than it needs to be. My code is staged here — just click on the polygon to generate a new one.
Happy coding.