2017-04-07 55 views
0

我想文件加载SVG成一个DIV(或其他),我甚至可以成功here做到这一点:D3。加载SVG文件并一次仅显示一个。衰落/更换问题

var div_svg = d3.select("div#example"); 

svg1 = "https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg"; 
svg2 = "https://upload.wikimedia.org/wikipedia/commons/8/81/Wikimedia-logo.svg"; 

var createSvg = function(dataset) { 
    d3.xml(dataset) 
    .mimeType("image/svg+xml") 
    .get(function(error, xml) { 
     if (error) throw error; 
     div_svg.node().append(xml.documentElement); 
    }); 
} 

update = function(dataset) { 
    div_svg.select('svg') 
     .style("opacity", 1) 
     .transition() 
     .duration(200) 
     .style("opacity", 0) 
     .remove(); 
    createSvg(dataset) 
} 

createSvg(svg1); 
d3.select("#one").on("click", function() { update(svg1); }); 
d3.select("#two").on("click", function() { update(svg2); }); 

但我有一些问题:

  1. 一旦你准备选择另一个文件,第一个文件应该会消失,但是另一个文件会在下面堆叠,直到以前消失为止。我怎样才能顺利取代一个svg?

  2. 如果我继续快速点击svg“按钮”,多个图形出现在div中。我可以做一个肮脏的修复,只是检查svg已被渲染,但我想弄清楚如何以更好的方式解决这个异步更新问题。

谢谢

回答

0

所以,我会做:等待你的已加载SVG做褪色prvious SVG的过渡后,然后等待转换完成,删除旧,加新的和淡入的:

var createSvg = function(dataset) { 
    d3.xml(dataset) 
      .mimeType("image/svg+xml") 
      .get(function(error, xml) { 
       d3.select("#example") 
         .select('svg') 
         .style("opacity", 1) 
         .transition() 
         .duration(200) 
         .style("opacity", 0); 

       setTimeout(function(){ 
        d3.select("#example") 
          .select('svg').remove(); 

        div_svg.node().append(xml.documentElement); 

        d3.select("#example") 
          .selectAll('svg') .select('svg') 
          .style("opacity", 0) 
          .transition() 
          .duration(200) 
          .style("opacity", 1); 
       }, 200); 

       if (error) throw error; 
      }); 
}; 

update = function(dataset) { 
    createSvg(dataset) 
};