Search code examples
javascripthtmlsvgjquery-svg

Getting issues in svg center point


Here is the code for finding the svg image center point and shows dots, but am getting error that el is null.Can anyone tell whats the mistake.Shall i add js library here.

 <!DOCTYPE html>
            <html>
            <head>
             <script type="text/javascript">

              var svg   = document.querySelector("svg");
              var svgns = "http://www.w3.org/2000/svg";

              // get the center
              var el = document.querySelector("path");
              var bbox = el.getBBox();
              var center = {
                 x: bbox.left + bbox.width/2,
                 y: bbox.top  + bbox.height/2
              };

              // create the dot
              var dot = document.createElementNS(svgns, circle);
              console.log(dot);
              dot.setAttribute("cx", center.x);
              dot.setAttribute("cy", center.y);
              dot.setAttribute("r", 10);
              svg.appendChild(dot);
            </script>
            </head>
            <body>

             <svg height="210" width="400" >
              <path d="M75 0 L56 105 L225 200 Z" />
            </svg> 

            </body>
            </html>

Solution

  • Instead of element.getBBox() try using element.getBoundingClientRect(); which seems to be working correctly:

              var svg   = document.querySelector("svg");
              var svgns = "http://www.w3.org/2000/svg";
    
              // get the center
              var el = document.querySelector("path");
              var bbox = el.getBoundingClientRect();
              var center = {
                 x: bbox.left + bbox.width/2,
                 y: bbox.top  + bbox.height/2
              };
    
              // create the dot
              var dot = document.createElementNS(svgns, "circle");
              console.log(dot);
              dot.setAttribute("cx", center.x);
              dot.setAttribute("cy", center.y);
              dot.setAttribute("r", 10);
              svg.appendChild(dot);
    

    Fiddle: http://jsfiddle.net/dd5kY/