这是找到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>

最佳答案

尝试使用似乎正常运行的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/

08-04 11:45