Positioning SVG Elements
Posted
by Rob Wilkerson
on Stack Overflow
See other posts from Stack Overflow
or by Rob Wilkerson
Published on 2010-04-29T15:36:08Z
Indexed on
2010/04/29
15:37 UTC
Read the original article
Hit count: 479
In the course of toying with SVG for the first time (using the Raphael library), I've run into a problem positioning dynamic elements on the canvas in such a way that they're completely contained within the canvas. What I'm trying to do is randomly position n words/short phrases.
Since the text is variable, its position needs to be variable as well so what I'm doing is:
- Initially creating the text at point
0,0
with no opacity. - Checking the width of the drawn text element using
text.getBBox().width
. - Setting a new
x
coordinate asMath.random() * (canvas_width - ( text_width/2 ) - pad)
. - Altering the
x
coordinate of the text to the newly set value (text.attr( 'x', x )
). - Setting the opacity attribute of the text to 1.
I'll be the first to admit that my math acumen is limited, but this seems pretty straightforward. Somehow, I still end up with text running off beyond the right edge of my canvas. For simplicity above, I removed the bit that also sets a minimum x
value by adding it to the Math.random()
result. It is there, though, and I see the same problem on the leading edge of the canvas.
My understanding (such as it is), is that the Math.random()
bits would generate a number between 0 and 1 which could then be multiplied by some number (in my case, the canvas width - half of the text width - some arbitrary padding) to get the outer bound. I'm dividing the width of the text in half because its position on the grid is set at its center.
I hope I've just been staring at this for too long, but is my math that rusty or am I misunderstanding something about the behavior of Math.random()
, SVG, text or anything else that's under the hood of this solution?
© Stack Overflow or respective owner