4
나는 순수한 JavaScript로 SVG 사각형을 그리려고합니다. 그것은 나타나지 않습니다.동적으로 생성 된 SVG 요소가 표시되지 않습니다.
그러나 브라우저 콘솔에서 document.getElementById('rect1')
을 실행하면 rectangle 요소가 존재합니다. 콘솔에서 HTML을 복사하여 HTML 파일에 붙여 넣으면 직사각형이 제대로 표시됩니다. 올바른 코드가 문서에 추가되는 것처럼 보이지만 요소가 표시되지 않습니다.
HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div>
<svg id="test" width="500" height="500">
<!-- code copied from browser console works
<rect x="30" y="60" width="50" height="80" style="stroke:#000000; fill:none;" id="rect1">
</rect> -->
</svg>
<svg id="main" width="500" height="500"></svg>
</div>
<script src="./src/shapes.js"></script>
</body>
</html>
자바 스크립트 :
function addSvgElement() {
var rect = document.createElement("rect");
rect.setAttribute('x', 30);
rect.setAttribute('y', 60);
rect.setAttribute('width', 50);
rect.setAttribute('height', 80);
rect.setAttribute('style', "stroke:#000000; fill:none;");
rect.id = "rect1";
var svg = document.getElementById('main');
svg.appendChild(rect);
}
addSvgElement(); // adds correct code, but element doesn't show up
보인다 :의 //jsfiddle.net/fpG4Z/ – sfletche
가능한 중복 (http://stackoverflow.com/questions/1034712/creating- [자바 스크립트를 사용하여 SVG 그래픽을 만들기?] –
@sfletche 죄송합니다. 사각형을 생성하는 HTML 파일의 코드가 브라우저 콘솔에서 복사되어 디버깅을 위해 문서에 붙여 넣어 졌음을 분명히하지 않았습니다. 그래도 사각형을 동적으로 생성하고 싶습니다. –