【问题标题】:Getting issues in svg center point在 svg 中心点出现问题
【发布时间】:2014-09-18 01:56:55
【问题描述】:

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

【问题讨论】:

    标签: javascript html svg jquery-svg


    【解决方案1】:

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

              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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-27
      • 2020-04-21
      • 2022-01-13
      • 2019-11-19
      • 2021-08-18
      • 2013-07-09
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多