如何获得SVG的背景颜色正确转换为Canvas [英] How to get background color of SVG converted properly into Canvas

查看:2466
本文介绍了如何获得SVG的背景颜色正确转换为Canvas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用canvg库将d3 svg对象转换为画布并将其显示为图像(png)。

Im converting a d3 svg object with use of canvg library to an canvas and display it as an image (png).

生成的图像具有透明背景,这不是我想要的。我需要这个与白色背景。

The resulting image has a transparent background, which is not what I want. I need this with a white background.

所以我试图设置svg元素的背景颜色。当查看svg元素是很好,但转换后的图像仍然是透明的。
我也试过修改canvas对象的背景,但是这也不行。

So i tried to set the background color of svg element. When viewing svg element it is fine, but the converted image is still transparent. I also tried, to alter background of the canvas object, but this is also not working.

第一种方法(svg):

first approach (svg):

var svg = d3.select(".chart").append("svg").attr("style","background: white;")...

第二个aproach(canvas):

second aproach (canvas):

canvg(document.getElementById('canvas'), $("#chart").html());

var canvas = document.getElementById('canvas');
canvas.style.background = 'white';
var img = canvas.toDataURL('image/png');
document.write('<img src="' + img + '"/>');  

有人知道,我必须在哪个对象上设置背景颜色,适当地在png图像?

Does anyone know, on which object I have to set the background color, in order to get it converted properly in png image ?

编辑:根据ThisOneGuys中提到的信息,我找到了这个解决方案。

With the information mentioned in ThisOneGuys answers, I found this solution.

var svg = d3.select(".chart").append("svg") ...

svg.append("rect")
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "white"); 

使用附加的rect,我得到我需要的:)

With the appended rect, I get what I need :)

推荐答案

我已经跑过去了。因为你知道CSS不会在DOM中传递get,所以它不会被转换读取。所以你必须做内联样式。但是你目前做的方式是不正确的。

I have ran in to this before. As you know the CSS doesn't pass get put in the DOM, so it's not read by the conversion. So you have to do inline styling instead. But the way you are currently doing it is incorrect.

因此,而不是使用:

.attr("style","background: white;").

您必须设置如下样式:

.style('fill', 'white'); 

这应该可以正常工作:)

That should work fine :)

这篇关于如何获得SVG的背景颜色正确转换为Canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆