Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript SVG Position in Pixels

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #206662
    justdan
    Participant

    Hey 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.

    #206665
    Shikkediel
    Participant

    This should give the correct output :

    x = svgPos.left + parseFloat($(ev.target).attr('cx')),
    y = svgPos.top + parseFloat($(ev.target).attr('cy')),
    
    #206668
    justdan
    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!

    #206678
    Shikkediel
    Participant

    Sure, no problem. Could it be you’re looking for the offset related to the parent? That would be position() because offset() 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.

    #206686
    justdan
    Participant

    Ah got it. My viewBox settings were WAY off. So after some adjusting the little piece you provided worked like a charm. Thanks again, @Shikkediel!

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.