在svg中心点获取问题

时间:2014-07-26 07:48:22

标签: javascript html svg jquery-svg

这是用于查找svg图像中心点并显示点的代码,但是我得到的错误是el为null。任何人都可以告诉我们错误。我在这里添加js库。

 <!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>

1 个答案:

答案 0 :(得分:4)

而不是element.getBBox()尝试使用似乎正常工作的element.getBoundingClientRect();

          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);

小提琴:http://jsfiddle.net/dd5kY/