如何通过JavaScript为SVG形状指定渐变填充?

时间:2010-06-23 08:49:07

标签: javascript html5 svg

我正在使用Raphael JavaScript库创建一个SVG矩形,并使用以下代码行为其指定填充:

this.myBox.attr({fill: 'white'});

这很好用。但是,现在我想把它与线性渐变联系起来。我借用了一些渐变代码来测试它,使用下面的代码:

<defs>
<linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);
stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);
stop-opacity:1"/>
</linearGradient>
</defs>

为了将其分配给形状,我尝试这样做:

this.myBox.attr({fill:url(#orange_red)});

在这种情况下,我收到错误'非法字符'#''。

我哪里错了?

2 个答案:

答案 0 :(得分:4)

this.myBox.attr({fill: "315-rgb(255,255,0)-rgb(255,0,0)"});

如果你将这种做法与线性渐变联系起来,那么它显然不适用于IE。如果你不关心IE,那么首先使用Raphaël有什么意义呢?

答案 1 :(得分:2)

你只是忘记引用值字符串。

this.myBox.attr({fill: 'url(#orange_red)'});

这是一个JavaScript的怪癖,在对象文字语法({ ... })中,名称部分fill并不总是需要引用为{{1 }}。但是,该值可以是任何类型,因此对于字符串始终需要引用。