2014-07-26 2 views
0

여기에 svg 이미지 중심점을 찾고 점을 표시하는 코드가 있지만 el이 null 인 오류가 발생했습니다. 누구든지 오류를 알 수 있습니까? 여기에 js 라이브러리를 추가하십시오. 대신 보인다 element.getBoundingClientRect();를 사용해보십시오 element.getBBox()svg 중심점에서 문제 받기

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

답변

4

가 제대로 작동합니다 :

  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/