2016-12-16 112 views
0

我已经尝试了这么多。什么都没有有人帮助我吗?SVG-JavaScript没有正确渲染

谢谢。

var svg = document.createElement("svg"); 
 
svg.setAttribute("width", "100%"); 
 
svg.setAttribute("height", "100%"); 
 

 
var line = document.createElement("line"); 
 
line.setAttribute("x1", "0"); 
 
line.setAttribute("y1", "0"); 
 
line.setAttribute("x2", "100"); 
 
line.setAttribute("y2", "100"); 
 
line.setAttribute("stroke", "black"); 
 
line.setAttribute("stroke-width", "4px"); 
 

 
svg.appendChild(line); 
 

 
document.body.appendChild(svg);

回答

1

以下应该工作。创建元素,并使用应用样式:

这使得它,这样的SVG和它的内部形状将范围内创建(因此– 命名空间)的SVG,而不是HTML文档。

var svgns = "http://www.w3.org/2000/svg"; 
 
var svg = document.createElementNS(svgns, "svg"); 
 
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 
 
svg.setAttributeNS(null, 'width', '100%'); 
 
svg.setAttributeNS(null, 'height', '100%'); 
 

 
var line = document.createElementNS(svgns, "line"); 
 
line.setAttributeNS(null, 'x1', 0); 
 
line.setAttributeNS(null, 'y1', 0); 
 
line.setAttributeNS(null, 'x2', 100); 
 
line.setAttributeNS(null, 'y2', 100); 
 
line.setAttributeNS(null, 'stroke', 'black'); 
 
line.setAttributeNS(null, 'stroke-width', 4); 
 
svg.appendChild(line); 
 

 
document.body.appendChild(svg);

简单,但仍然有效:

var svgns = "http://www.w3.org/2000/svg"; 
 
var svg = document.createElementNS(svgns, "svg"); 
 
svg.setAttribute('width', '100%'); 
 
svg.setAttribute('height', '100%'); 
 

 
var line = document.createElementNS(svgns, "line"); 
 
line.setAttribute('x1', 0); 
 
line.setAttribute('y1', 0); 
 
line.setAttribute('x2', 100); 
 
line.setAttribute('y2', 100); 
 
line.setAttribute('stroke', 'black'); 
 
line.setAttribute('stroke-width', 4); 
 
svg.appendChild(line); 
 

 
document.body.appendChild(svg);

+0

这是什么NS? – Timo

+0

NS是命名空间的缩写 –