shuji
shuji

Reputation: 7527

How to create a pattern with Raphaeljs?

I'm trying to add a grid pattern to my shapes, is there something I'm missing? This is the way I added it:

** Fiddle **

var paper = new Raphael(document.getElementById('canvas_container'), '100%', '100%');
$('<pattern id="mygrid" width="10" height="10" patternUnits="userSpaceOnUse">\
    <polygon points="5,0 10,10 0,10" stroke="black" />\
    </pattern>').appendTo('svg defs');

var circle = paper.circle(60, 60, 50);
circle.attr("fill","url(#mygrid)");

I think it's probably because the document is loaded before I add the pattern
This is the html after the pattern is added (the circle is not being fill):

<div id=canvas_container>
<svg height="100%" version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative;">
    <desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.2</desc>
    <defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
        <pattern id="mygrid" width="10" height="10" patternunits="userSpaceOnUse">
        <polygon points="5,0 10,10 0,10" stroke="black"></polygon>
        </pattern>
        <pattern id="6A35489A-D006-4344-B2A5-C3899E2C21F4" x="0" y="0" patternUnits="userSpaceOnUse" height="1" width="1" patternTransform="matrix(1,0,0,1,0,0) translate(9.925405384842906,10)" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
        <image x="0" y="0" xlink:href="#mygrid" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></image>
        </pattern>
    </defs>
    <circle cx="60" cy="60" r="50" fill="url(#6A35489A-D006-4344-B2A5-C3899E2C21F4)" stroke="#000" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></circle>
</svg>
</div>

Upvotes: 0

Views: 1407

Answers (1)

shuji
shuji

Reputation: 7527

Thank you Robert for pointing me to the right direction
Elements with an xhtml namespace cannot be added the same way as other elements
(I had to create another svg entirely with my pattern and then copy it)
This is the way I made it work:

var dummy = $('<svg style="display:none"><defs>\
    <pattern id="mygrid" width="30" height="30" patternUnits="userSpaceOnUse">\
    <polygon points="15,0 30,30 0,30" stroke="black" />\
    </pattern></defs></svg>').appendTo('body');
$(paper.canvas).append(dummy.find("#mygrid")); //paper.canvas is the svg node
dummy.remove();

"if the whole SVG document is appended, then the browser handles automatically the namespace conversion of all the elements in SVG document."

or:

var pattern = '<pattern id="mygrid" width="30" height="30" patternUnits="userSpaceOnUse">\
    <polygon points="15,0 30,30 0,30" stroke="black" />\
    </pattern>';
pattern = $.parseHTML('<svg>'+pattern+'</svg>')[0].firstChild; //or childNodes
$('svg defs').append(pattern);

Upvotes: 1

Related Questions