Dynamically adding a SVG gradient

前端 未结 4 637
庸人自扰
庸人自扰 2020-12-10 05:38

I have this SVG container with paths. I want to edit it, so the paths\' fill will be a pattern. This is my failed attempt:

I add a gradient:

$(\'svg          


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 05:55

    Your problem (what you are "missing") is that jQuery creates new elements in the XHTML namespace, while SVG elements must be created in the SVG namespace. You cannot use raw code in a string for SVG elements.

    The simplest (no-plugins) method is to stop leaning on jQuery so much and just use simple DOM methods to create the elements. Yes, it's more verbose than just using jQuery to magically construct your elements for you...but jQuery does not work in this 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:   the owning  element
    // id:    an id="..." attribute for the gradient
    // stops: an array of objects with  attributes
    function createGradient(svg,id,stops){
      var svgNS = svg.namespaceURI;
      var grad  = document.createElementNS(svgNS,'linearGradient');
      grad.setAttribute('id',id);
      for (var i=0;i

    Using a Library

    Alternatively, you can include Keith Woods' "jQuery SVG" plugin that has a lot of convenience methods for common SVG operations, including the ability to create linear gradients.

提交回复
热议问题