无法创建svg

时间:2016-09-04 13:49:32

标签: javascript svg polyline

我正在尝试使用javascript创建svgpolyline

虽然它正确地创造了&附加元素,但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 个答案:

答案 0 :(得分: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>