Home › Forums › JavaScript › SVG Position in Pixels
- This topic is empty.
-
AuthorPosts
-
August 17, 2015 at 9:54 am #206662
justdan
ParticipantHey guys. I’m working on a little something that is using an SVG map that plots an svg circle on it based off of zip codes. I have everything I need but now I would like to get the positions of each svg circle. I have a little script to get the current positions, but I have run into 2 problems. A) First off all what is the unit of measurement for the cx and cy coordinates? And B) How can I convert the x and y coords to pixels? I’ll include the code I’m using and what it logs below:
$('circle').on('click', function(ev) { var svgPos = $('svg').offset(), x = svgPos.left + $(ev.target).attr('cx'), y = svgPos.top + $(ev.target).attr('cy'), svgcoords = [x, y]; console.log(svgcoords) });
Using this and clicking on one of the svg circles will give me coords like:
["101555.3774402917326", "522.78125367.3909667019818"]
Here’s where I can’t seem to find what I’m after. How can I get those numbers in pixels? Assuming you can even do that. My current SVG knowledge is pretty limited so any tips or help would be great. Thanks guys.
August 17, 2015 at 10:47 am #206665Shikkediel
ParticipantThis should give the correct output :
x = svgPos.left + parseFloat($(ev.target).attr('cx')), y = svgPos.top + parseFloat($(ev.target).attr('cy')),
August 17, 2015 at 11:12 am #206668justdan
Participant@Shikkediel Thanks for that response. Totally forgot I could trim those up like that. That’s one part down, not I just need to figure out the conversion. Even though the parseFloat gives me a much nicer looking number, it’s still not the correct pixel amount. I cannot seem to find a way around this. More hunting for answers… Thanks again for the reply!
August 17, 2015 at 1:22 pm #206678Shikkediel
ParticipantSure, no problem. Could it be you’re looking for the offset related to the parent? That would be
position()
becauseoffset()
refers to the window. I made a pen to check before and it seemed correct. If you mean something different, you could always post another small example and we could troubleshoot some more.August 17, 2015 at 4:39 pm #206686justdan
ParticipantAh got it. My viewBox settings were WAY off. So after some adjusting the little piece you provided worked like a charm. Thanks again, @Shikkediel!
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.