2016-09-04 79 views
0

我正在嘗試使用javascript創建svg,polyline無法創建svg

雖然它是正確創建&附加元素,但polyline不繪製在屏幕上。

var _button = document.createElement('button'); 
    _button.id = "scrollToTop"; 
    _button.class = ""; 

    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 
    svg.setAttribute('style', 'border: 1px solid black'); 
    svg.setAttribute('width', '600'); 
    svg.setAttribute('height', '250'); 
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 

    var _polyline = document.createElement('polyline'); 
    _polyline.setAttribute("fill", "#006600"); 
    _polyline.setAttribute("stroke", "#FFFFFF"); 
    _polyline.setAttribute('stroke-width', '1'); 
    _polyline.setAttribute('stroke-linecap', 'round'); 
    _polyline.setAttribute('stroke-linejoin', 'round'); 
    _polyline.setAttribute("points", "10,52 60,52 35,0"); 

document.getElementById('scrollToTop').appendChild(svg).appendChild(_polyline); 

請幫助解決這個問題

JSFIDDLE

回答

1

你忘記了命名空間:

var _polyline = document.createElementNS("http://www.w3.org/2000/svg", 'polyline'); 
_polyline.setAttribute("fill", "#006600"); 
_polyline.setAttribute("stroke", "#FFFFFF"); 
_polyline.setAttribute('stroke-width', '1'); 
_polyline.setAttribute('stroke-linecap', 'round'); 
_polyline.setAttribute('stroke-linejoin', 'round'); 
_polyline.setAttribute("points", "10,52 60,52 35,0"); 

這是你的工作代碼:

var _button = document.createElement('button'); 
 
    _button.id = "scrollToTop"; 
 
    _button.class = ""; 
 

 
    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 
 
    svg.setAttribute('style', 'border: 1px solid black'); 
 
    svg.setAttribute('width', '600'); 
 
    svg.setAttribute('height', '250'); 
 
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 
 

 
    var _polyline = document.createElementNS("http://www.w3.org/2000/svg", 'polyline'); 
 
    _polyline.setAttribute("fill", "#006600"); 
 
    _polyline.setAttribute("stroke", "#FFFFFF"); 
 
    _polyline.setAttribute('stroke-width', '1'); 
 
    _polyline.setAttribute('stroke-linecap', 'round'); 
 
    _polyline.setAttribute('stroke-linejoin', 'round'); 
 
    _polyline.setAttribute("points", "10,52 60,52 35,0"); 
 

 
document.getElementById('scrollToTop').appendChild(svg).appendChild(_polyline);
<div id="scrollToTop"></div>