How to create gradient object with Raphael

tarella picture tarella · Feb 22, 2009 · Viewed 17.8k times · Source

I was trying to use Raphael JS graphics library. I would like to use the attribute gradient which should accept an object. Documentation says to refer to SVG specs. I found the gradient object in SVG, for instance

<linearGradient id="myFillGrad" x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="5%" stop-color="red" />
<stop offset="95%" stop-color="blue" stop-opacity="0.5" />
</linearGradient>

but how can I reference that from within my javascript?

circle.attr("gradient", "myFillGrad"); 

doesn't work :) Thanks in advance

Answer

Nathan de Vries picture Nathan de Vries · Feb 25, 2009

UPDATE: Rewritten for the latest Raphael API:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Linear Gradient</title>
  <script src="http://raphaeljs.com/raphael.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
  <script type="text/javascript" charset="utf-8">
    var paper = Raphael(10, 10, 800, 600);
    var circle = paper.circle(150, 150, 150);
    circle.attr({
      "fill": "90-#f00:5-#00f:95",
      "fill-opacity": 0.5
    });
  </script>
</body>
</html>

The documentation for the new attr() API is found here.