D3.js 中实现svg 保存 png

来源:互联网 发布:excel2010数据按钮 编辑:程序博客网 时间:2024/05/22 10:31

直接上代码:


//svg 保存成Png  fuctionfunction svgToPng(svg,pngWidth,pngHeight){ var serializer = new XMLSerializer();       var source = '<?xml version="1.0" standalone="no"?>\r\n'+serializer.serializeToString(svg.node());       var image = new Image;       image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source);       var canvas = document.createElement("canvas");           canvas.width = pngWidth;           canvas.height = pngHeight;      var context = canvas.getContext("2d");       context.fillStyle = '#fff';//设置保存后的PNG 是白色的     context.fillRect(0,0,10000,10000);     context.drawImage(image, 0, 0);       return canvas.toDataURL("image/png");   }
使用方法:

 $('#imgSave').click(function(){               var url=svgToPng(svg,width,height);               var pngName="svgtoPng图";               var a = document.createElement("a");                        a.download = pngName+".png";                        a.href = url;                        a.click();       })

参数介绍:

svg 是D3 创建的,代码如下:

 var svg = d3.select("#jftp").append("svg")                    .attr("width", width)                    .attr("height",height);

width,height   根据需求设置

 var width = $(document).width()-20; var height = $(document).height()-108;

问题总结:

下载后 图片这种情况:原因是

linkEnter.append("path")       //  .attr("class", "link")//  使用了css 控制了连线格式 而 这种控制 在导出图片时,不能控制样式//setting the styles through CSS. This doesn't generally work well with rendering to PNG;         .attr("style", "fill: none; stroke-opacity: 1;stroke-width: 1.5px;")//正确方法应该是 直接css在代码中控制。          .attr("d", function(d) {                var o = {x: data.x0, y: data.y0};                 return diagonal({source: o, target: o});                 })          .transition()          .duration(500)          .attr("d", diagonal);




0 0