最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to assign gradient fill to SVG shape via JavaScript? - Stack Overflow

programmeradmin1浏览0评论

I'm creating an SVG rectangle using the Raphael JavaScript library, and assigning it a fill using the following line of code:

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

This works fine. However, now I want to tie this to a linear gradient. I have borrowed some gradient code to test it out, using the code below:

<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>

And in order to assign this to the shape, I tried doing this:

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

In this case, I get the error 'Illegal character '#''.

Where am I going wrong?

I'm creating an SVG rectangle using the Raphael JavaScript library, and assigning it a fill using the following line of code:

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

This works fine. However, now I want to tie this to a linear gradient. I have borrowed some gradient code to test it out, using the code below:

<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>

And in order to assign this to the shape, I tried doing this:

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

In this case, I get the error 'Illegal character '#''.

Where am I going wrong?

Share Improve this question asked Jun 23, 2010 at 8:49 Jack RoscoeJack Roscoe 4,34310 gold badges38 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

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

If you will tie this to linear gradient the way you do, it obviously wouldn’t work in IE. And if you don’t care about IE, then what the point to use Raphaël in the first place?

You've simply forgotten to quote the value string.

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

It is a quirk of JavaScript that in the object literal syntax ({...}) the name part fill doesn't always need to be quoted as 'fill'. However the value can be of any type and so for strings always needs to be quoted.

发布评论

评论列表(0)

  1. 暂无评论