HTML5画布.toDataURL()图像没有背景色

17

问题

当使用HTML5的<canvas>元素的.toDataURL()方法时,元素的background-color属性不会应用于图片。这是因为background-color实际上不是canvas的一部分,而是DOM样式吗?如果是,还有什么替代方法吗?

Fiddle

可以在这里玩弄Fiddle。base64字符串已记录到控制台。

额外信息

Canvas是从svg中创建的,使用的是https://code.google.com/p/canvg/


3
你试过在你的“画布”上画一个正确颜色的大矩形吗? - robertc
@robertc在使用.drawSvg时运行良好,但使用canvg()时没有成功。 - Artyom Neustroev
3个回答

43

另一种方法是创建一个虚拟的 CANVAS,并将原始 CANVAS 的内容复制到其中。

//create a dummy CANVAS

destinationCanvas = document.createElement("canvas");
destinationCanvas.width = srcCanvas.width;
destinationCanvas.height = srcCanvas.height;

destCtx = destinationCanvas.getContext('2d');

//create a rectangle with the desired color
destCtx.fillStyle = "#FFFFFF";
destCtx.fillRect(0,0,srcCanvas.width,srcCanvas.height);

//draw the original canvas onto the destination canvas
destCtx.drawImage(srcCanvas, 0, 0);

//finally use the destinationCanvas.toDataURL() method to get the desired output;
destinationCanvas.toDataURL();

2
这应该是正确的答案...为这样一个漂亮的答案苦苦挣扎...之前的答案使整个图像变白。干得好!!! - Sheetal
是的,将源代码复制到新画布中绝对是更好的解决方案。谢谢。 - Vyacheslav Tsivina
惊人的解决方案,我之前使用getImageData但对于透明背景不起作用。 - Professor Dragon

12

你是正确的,这实际上不是图像数据的一部分,而只是样式的一部分。最简单的方法是在绘制SVG之前先绘制一个矩形:

var canvas = document.getElementById('test');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, canvas.width, canvas.height);

是的,这对.drawSvg有效,但对于canvg()无效http://jsfiddle.net/qDmhV/159/。有什么想法为什么? - Artyom Neustroev
2
尝试将 ingoreClear 更改为 ignoreClear。 ;) - ZachRabbit

0

希望这能有所帮助,

var canvas = document.getElementById('test');

var context = canvas.getContext('2d');

//cache height and width        
var w = canvas.width;
var h = canvas.height;

var data = context.getImageData(0, 0, w, h);

var compositeOperation = context.globalCompositeOperation;

context.globalCompositeOperation = "destination-over";
context.fillStyle = "#fff";
context.fillRect(0,0,w,h);

var imageData = canvas.toDataURL("image/png");

context.clearRect (0,0,w,h);
context.putImageData(data, 0,0);        
context.globalCompositeOperation = compositeOperation;

var a = document.createElement('a');
a.href = imageData;
a.download = 'template.png';
a.click();

1
请在您的代码中提供一些解释性内容。 - wscourge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接