【问题标题】:d3.js - svg filter equivalent with d3.jsd3.js - 与 d3.js 等效的 svg 过滤器
【发布时间】:2021-09-15 16:41:38
【问题描述】:

我从 svg 文件中得到了下面的 svg 过滤器:

   <defs>
      <filter height="300%" id="blurfilter" width="300%" x="-1" y="-1">
         <feGaussianBlur result="blurOut" stdDeviation="2.0" />
         <feColorMatrix in="blurOut" result="blurOut2" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 0" />
         <feOffset dx="4.0" dy="4.0" in="blurOut2" result="blurOut3" />
         <feBlend in="SourceGraphic" in2="blurOut3" mode="normal" />
      </filter>
   </defs>

用 d3.js 实现它的正确方法是什么?

我尝试下面的代码,但看起来不正确:

 svg.append('defs')
    .append('filter')
    .attr('width','300%')
    .attr('id','blurfilter')
    .attr('x',-1)
    .attr('y',-1)
    .append('feGaussianBlur')
    .attr('result','blurOut')
    .attr('stdDeviation',2.0)
    .append('feColorMatrix')
    .attr('id','blurOut')
    .attr('result','blurOut2')
    .attr('type','matrix')
    .attr('values','0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 0')
    .append('feOffset')
    .attr('dx',4.0)
    .attr('dy',4.0)
    .attr('in','blurOut2')
    .attr('result','blurOut3')
    .append('feBlend')
    .attr('in','SourceGraphic')
    .attr('in2','blurOut3')
    .attr('mode','normal')

【问题讨论】:

    标签: svg d3.js svg-filters


    【解决方案1】:

    需要断链,目前追加如下:

     svg.append('defs')
        .append('filter')
        ...
        .append('feGaussianBlur')
        ...
        .append('feColorMatrix')
        ...
        .append('feOffset')
        ...
        .append('feBlend')
    

    每次使用 .append() 时,都会返回一个新选择的附加元素。因此,您将 feBlend 元素附加到父 feOffset 元素,而不是过滤器本身。例如:

       <defs>
          <filter height="300%" id="blurfilter" width="300%" x="-1" y="-1">
             <feGaussianBlur result="blurOut" stdDeviation="2.0">
                 <feColorMatrix in="blurOut" result="blurOut2" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .4 0" >
                     <feOffset dx="4.0" dy="4.0" in="blurOut2" result="blurOut3" >
                         <feBlend in="SourceGraphic" in2="blurOut3" mode="normal" />
                     </feOffset>
                  </feColorMatrix>
              </feGaussianBlur>
          </filter>
       </defs>
    

    相反,打破链并附加到过滤器的选择中:

    var filter = svg.append('defs')
      .append('filter')
      .attr(...
    
    filter.append('feGaussianBlur')
      .attr(...
    
    filter.append('feColorMatrix')
      .attr(...
    
    filter.append('feOffset')
       .attr(...
    
    filter.append('feBlend')
       .attr(...
    

    这将为您提供与示例相同的 DOM 结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多