javascript - Dynamically adding a SVG gradient -
i have svg container paths. want edit it, paths' fill pattern. failed attempt:
i add gradient:
$('svg defs').prepend('<lineargradient id="mygradient"><stop offset="5%" stop-color="#f60" /><stop offset="95%" stop-color="#ff6" /></lineargradient>'); and change paths' fill:
$(base + ' svg path').each(function() { this.setattribute('fill','url(#mygradient)') } this doesn't work. missing?
your problem (what "missing") jquery creates new elements in xhtml namespace, while svg elements must created in svg namespace. cannot use raw code in string svg elements.
the simplest (no-plugins) method stop leaning on jquery , use simple dom methods create elements. yes, it's more verbose using jquery magically construct elements you...but jquery not work in case.
demo: http://jsfiddle.net/nra29/2/
creategradient($('svg')[0],'mygradient',[ {offset:'5%', 'stop-color':'#f60'}, {offset:'95%','stop-color':'#ff6'} ]); $('svg path').attr('fill','url(#mygradient)'); // svg: owning <svg> element // id: id="..." attribute gradient // stops: array of objects <stop> attributes function creategradient(svg,id,stops){ var svgns = svg.namespaceuri; var grad = document.createelementns(svgns,'lineargradient'); grad.setattribute('id',id); (var i=0;i<stops.length;i++){ var attrs = stops[i]; var stop = document.createelementns(svgns,'stop'); (var attr in attrs){ if (attrs.hasownproperty(attr)) stop.setattribute(attr,attrs[attr]); } grad.appendchild(stop); } var defs = svg.queryselector('defs') || svg.insertbefore( document.createelementns(svgns,'defs'), svg.firstchild); return defs.appendchild(grad); } using library
alternatively, can include keith woods' "jquery svg" plugin has lot of convenience methods common svg operations, including ability create linear gradients.
Comments
Post a Comment