我正在使用带有相关线的d3散点图。一切都很好。当我添加下载按钮时,它可以下载图像,但图像中缺少线条。我正在使用以下功能下载图像。
d3.select("#downloadplot").on("click", function(){
var html = d3.select("svg")
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node( ).parentNode.innerHTML; //node().parentNode.innerHTML;
//console.log(html);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var image = new Image;
image.src = imgsrc;
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.fillStyle = "#FFFFFF";
context.fillRect(0,0,image.width,image.height);
context.drawImage(image, 0, 0);
var a = document.createElement('a');
a.download = "sampleidvgraph.png";
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
a.click().attr('target', '_blank');
}
});
原始散点图的链接示例: http://prcweb.co.uk/lab/what-makes-us-happy/ 这里是下载图片 原始散点图
附加行的代码:
// Best fit line (to appear behind points)
d3.select('svg g.chart')
.append('line')
.attr('id', 'bestfit');
和
// Fade in
d3.select('#bestfit')
.style('opacity', 0)
.attr({'x1': xScale(x1), 'y1': yScale(y1), 'x2': xScale(x2), 'y2': yScale(y2)})
.transition()
.duration(1500)
.style('opacity', 1);
答案 0 :(得分:3)
由于您用于下载SVG的功能仅依赖于SVG内容,因此请在D3代码中设置stroke
和stroke-width
,而不是在CSS中设置:
d3.select('#bestfit')
.style('opacity', 0)
.style("stroke", "red")//set the colour here
.style("stroke-width", 2)//set the width here
.attr({
'x1': xScale(x1),
'y1': yScale(y1),
'x2': xScale(x2),
'y2': yScale(y2)
})
.transition()
.duration(1500)
.style('opacity', 1);