본문 바로가기
HTML5/SVG

[SVG] document.createElementNS

by Jundol 2015. 10. 5.



document.createElementNS

네임스페이스를 사용하여 새 Element 노드를 생성한다. SVG는 XHTML 언어이므로 동적으로 생성할때는 createElement 를 사용하면 안되고 createElementNS 를 사용해야 한다.

createElement 를 사용해서 동적 삽입할 경우 개발자도구의 태그에는 추가된것으로 보이지만, 실제로 화면에 그려지진 않는다.


element = document.createElementNS(namespaceURI, qualifiedName);

parameter

namespaceURI : 새 element 에 대한 네임스페이스를 가리키는 유일한 식별자다. 네임스페이스가 없다면 null이 할당된다.

qualifiedName: 새 element에 대한 완결된 이름. 


return 값

element : 지정된 name 과 namespace를 갖는 새로 생성된 Element 노드.


사용 예

 - 동적생성으로 SVG 를 삽입하고싶을때 사용할 수 있는 함수를 만들어보자

 - 동적으로 SVG 태그를 만들고 rect 를 svg에 붙이는 소스코드.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
(function(){
	NS = {
		HTML: 'http://www.w3.org/1999/xhtml',
        MATH: 'http://www.w3.org/1998/Math/MathML',
        SE: 'http://svg-edit.googlecode.com',
        SVG: 'http://www.w3.org/2000/svg',
        XLINK: 'http://www.w3.org/1999/xlink',
        XML: 'http://www.w3.org/XML/1998/namespace',
        XMLNS: 'http://www.w3.org/2000/xmlns/' // see http://www.w3.org/TR/REC-xml-names/#xmlReserved
	};

	SVG = document.createElementNS(NS.SVG, "svg");

	browser = {
		isOpera : function(){
			return !!window.opera;
		},
		supportsSelectors: function(){
			return !!SVG.querySelector;
		},
		supportsXpath: function(){
			return !!document.evaluate;
		}
	};

	if(browser.supportsSelectors()){
		getElem = function(id){
			return SVG.querySelector("#" + id);
		};
	} else if (browser.supportsXpath()){
		getElem = function (id) {
            // xpath lookup
            return domdoc_.evaluate(
                'svg:svg[@id="svgroot"]//svg:*[@id="' + id + '"]',
                domcontainer_,
                function () { return WPod.svgedit.NS.SVG; },
                9,
                null).singleNodeValue;
        };
	} else {
		getElem = function(id){
			return $(SVG).find('[id=' + id + ']')[0];
		};
	};

	assignAttributes = function(node, attrs, suspendLength){
		if(!suspendLength){
			suspendLength = 0;
		}

		var handle = null;

		if(!browser.isOpera()){
			SVG.suspendRedraw(suspendLength);
		}

		var i;
		for(i in attrs){
			var ns = (i.substr(0,4) === 'xml:' ? NS.XML :
				i.substr(0,6) === 'xlink:' ? NS.XLINK : null);

			if(ns){
				node.setAttributeNS(ns, i, attrs[i]);
			} else {
				node.setAttribute(i, attrs[i]);
			}
		}

		if(browser.isOpera()) {
			SVG.unsuspendRedraw(handle);
		}
	}

	addSvgElementFromJson = function(data){
		var shape = getElem(data.attr.id);

		if(shape && data.element != shape.tagName){
			shape = null;
		}

		if(!shape){
			shape = document.createElementNS(NS.SVG, data.element);
		}
		assignAttributes(shape, data.attr, 100);
		return shape;
	}

	var svg = addSvgElementFromJson({
		"element":"svg",
		"attr":{
			"width": 500,
			"height": 500,
			"border": "solid 1px #000000"
		}
	});

	document.body.appendChild(svg);

	// 사용법
	var rect = addSvgElementFromJson({
		"element": "rect",
		"attr": {
			"id": "svg_rect",
			"x": 10,
			"y": 10,
			"width": 100,
			"height": 100,
			"fill": "red",
			"stroke": "solid"
		}
	});

	svg.appendChild(rect);
})();




'HTML5 > SVG' 카테고리의 다른 글

[SVG] SVG matrix interface  (0) 2015.11.23
[SVG] preserveAspectRatio 고정종횡비  (0) 2015.10.19
SVG Editor 분석-3 Path 포인트 정의하기  (0) 2015.06.15
SVG pathsegType  (0) 2015.06.15
SVG Editor 분석-2 객체 추가  (0) 2015.06.12

댓글