我可以在 html 正文中成功完成此工作,例如...
<div id="myContainer" style="float: left; background-color: Blue; height: 100px;
width: 100px;">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%">
<defs>
<lineargradient id="myLinearGradient" x1="0%" x2="0%" y1="0%" y2="100%">
<stop id="start" offset="50%" style="stop-color: White; stop-opacity: 1" />
<stop id="stop" offset="60%" style="stop-color: #99cd9f; stop-opacity: 1" />
</lineargradient>
</defs>
<circle cx="50px" cy="50px" r="50px" fill="url(#myLinearGradient)" />
</svg>
</div>
但是,我需要使用 javascript 动态创建它。只创建圆圈效果很好,当我将圆圈的填充指向线性渐变时它会失败 - 我只是得到一个黑色圆圈。
我想我没有正确设置 stop 'style' 属性。我尝试了另一种方法无济于事,请参见下文...
我正在使用 Chrome,在此先感谢!
在正文标签内:
<body>
<div style="float: left; background-color: Blue; height: 100px;
width: 100px;">
<svg id="Svg1" xmlns="http://www.w3.org/2000/svg">
<defs id="mydefs">
</defs>
</svg>
</div>
</body>
My script:
<script>
// lineargradient
var myLinearGradient = document.createElementNS("http://www.w3.org/2000/svg", "lineargradient");
myLinearGradient.setAttribute("id", "myLGID");
myLinearGradient.setAttribute("x1", "0%");
myLinearGradient.setAttribute("x2", "0%");
myLinearGradient.setAttribute("y1", "0%");
myLinearGradient.setAttribute("y2", "100%");
document.getElementById("mydefs").appendChild(myLinearGradient);
//stops
var stop1 = document.createElementNS("http://www.w3.org/2000/svg", "stop");
stop1.setAttribute("id", "myStop1");
stop1.setAttribute("offset", "70%");
//stop1.setAttribute("style", "stop-color: White; stop-opacity: 1");
stop1.setAttribute("stop-color", "White");
document.getElementById("mydefs").appendChild(stop1);
var stop2 = document.createElementNS("http://www.w3.org/2000/svg", "stop");
stop2.setAttribute("id", "myStop2");
stop2.setAttribute("offset", "80%");
//stop2.setAttribute("style", "stop-color: #99cd9f; stop-opacity: 1");
stop2.setAttribute("stop-color", "#99cd9f");
document.getElementById("mydefs").appendChild(stop2);
// Circle
var myCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
myCircle.setAttribute("id", "idCircle");
myCircle.setAttribute("cx", "50px");
myCircle.setAttribute("cy", "50px");
myCircle.setAttribute("r", "50px");
myCircle.setAttribute("fill", "url(#myLGID)");
document.getElementById("Svg1").appendChild(myCircle);
</script>