商会资讯
标题:
D3.js 中实现svg 保存 png
[打印本页]
作者:
admin
时间:
2017-1-17 14:02
标题:
D3.js 中实现svg 保存 png
[javascript]
view plain
copy
//svg 保存成Png fuction
function 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");
}
使用方法:
[javascript]
view plain
copy
$('#imgSave').click(function(){
var url=<span style="color:#FF0000;">svgToPng(svg,width,height);</span>
var pngName="svgtoPng图";
var a = document.createElement("a");
a.download = pngName+".png";
a.href = url;
a.click();
})
参数介绍:
svg 是D3 创建的,代码如下:
[javascript]
view plain
copy
var svg = d3.select("#jftp").append("svg")
.attr("width", width)
.attr("height",height);
width,height 根据需求设置
[javascript]
view plain
copy
var width = $(document).width()-20;
var height = $(document).height()-108;
问题总结:
下载后 图片这种情况:原因是
[javascript]
view plain
copy
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);
欢迎光临 商会资讯 (http://smellage.com/)
Powered by Discuz! X2.5