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

HTML5 canvas .toDataURL() image has no background color

本文关键字:背景色 图像 canvas toDataURL HTML5      更新时间:2023-09-26

问题

当使用HTML5 <canvas>元素的.toDataURL()方法时,该元素的background-color属性不应用于图片。

问题

发生这种情况是因为background-color实际上不是canvas的一部分,而是DOM样式吗?如果是这样,或者其他什么,有什么解决办法?

Fiddle

Fiddle在此处玩。base64字符串记录到控制台。

其他信息

画布是使用svg创建的https://code.google.com/p/canvg/

其他方法可以是创建一个虚拟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();

您认为它实际上不是图像数据的一部分,只是样式的一部分。最简单的方法是在绘制SVG之前只绘制一个矩形:

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

希望这会有所帮助,

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();