Scaling a fill pattern in raphael.js

barbarianbob picture barbarianbob · Jul 8, 2009 · Viewed 8.3k times · Source
paper=Raphael('previewBody',480,480);
paper.path({"stroke-width":1},'M0,0 L480,240 L480,480 L240,480 z')
  .attr('fill','url(bg.png)'))
  .scale(.5,.5,0,0);

My problem is the fill is not scaled with the svg canvas, so proportionally, it ends up as twice the size it was before the scale of the path. Is there any easy way to scale the fill pattern along with the rest of the svg?

Answer

ThibThib picture ThibThib · Jul 8, 2009

It is note possible to do it by using only the functions of the raphael library.

When you apply the scale function on a raphael's object, it creates a new svg node, with the coordinates scaled, but unfortunately, it doesn't modify the fill properties

Anyway, when you add the attribute "fill" with an url, the library create a pattern. If it is the first "fill" attribute that you use, this pattern is called raphael-pattern-0 the next one is called raphael-pattern-1, etc...)

Knowing this, it is then possible to change the attribute of the pattern, according to the SVG specifications

You can get the attributes of the pattern with document.getElementById("raphael-pattern-0") and change its properties with the setAttribute For example (depending on what you really want to do), it could be something like:

var pat = document.getElementById("raphael-pattern-0");
pat.setAttribute("height", pat.getAttribute("height")*0.5);
pat.setAttribute("width", pat.getAttribute("width")*0.5);

You can also modify the x, y, patternUnits and patternContentUnits properties.

Hope it will answer your question.