无法使用javacsript渲染SVG,而HTML可以使用SVG渲染

时间:2019-12-19 04:22:50

标签: javascript html svg

我正在尝试使用JavaScript创建SVG元素,但无法理解为什么无法呈现。这是我使用javascript渲染单圈动画的工作。

const svg = document.createElement("svg");
svg.setAttribute("width",120);
svg.setAttribute("height",30);
svg.setAttributeNS(null,"viewBox","0 0 120 30");
svg.setAttribute("xmlns","http://www.w3.org/2000/svg");
svg.setAttribute("fill","#f58c87");

const circleLeft = document.createElement("circle");
circleLeft.setAttribute("cx", "15");
circleLeft.setAttribute("cy", "15");
circleLeft.setAttribute("r", "15");

const animateOneLeft = document.createElement("animate");
animateOneLeft.setAttributeNS(null,"attributeName","r");
animateOneLeft.setAttribute("from",15);
animateOneLeft.setAttribute("to",15);
animateOneLeft.setAttribute("begin","0s");
animateOneLeft.setAttribute("dur","0.8s");
animateOneLeft.setAttribute("values", "15;9;15");
animateOneLeft.setAttributeNS(null,"calcMode","linear");
animateOneLeft.setAttributeNS(null,"repeatCount","indefinite");
circleLeft.append(animateOneLeft);

const animateTwoLeft = document.createElement("animate");
animateTwoLeft.setAttributeNS(null,"attributeName","fill-opacity");
animateTwoLeft.setAttribute("from","1");
animateTwoLeft.setAttribute("to","1");
animateTwoLeft.setAttribute("begin","0s");
animateTwoLeft.setAttribute("dur","0.8s");
animateTwoLeft.setAttribute("values","1;.5;1");
animateTwoLeft.setAttributeNS(null,"calcMode","linear");
animateTwoLeft.setAttributeNS(null,"repeatCount","indefinite");
circleLeft.append(animateTwoLeft);

svg.append(circleLeft);
document.body.append(svg);

如果我用HTML编写相同的内容,则可以正常工作,如下所示:

<svg width="120" height="30" viewBox="0 0 120 30" xmlns="http://www.w3.org/2000/svg" fill="#f58c87">
    <circle cx="15" cy="15" r="15">
        <animate attributeName="r" from="15" to="15"
                 begin="0s" dur="0.8s"
                 values="15;9;15" calcMode="linear"
                 repeatCount="indefinite" />
        <animate attributeName="fill-opacity" from="1" to="1"
                 begin="0s" dur="0.8s"
                 values="1;.5;1" calcMode="linear"
                 repeatCount="indefinite" />
    </circle>
</svg>

我用JavaScript做错了什么?

0 个答案:

没有答案