问题
当使用HTML5的<canvas>
元素的.toDataURL()
方法时,元素的background-color
属性不会应用于图片。这是因为background-color
实际上不是canvas
的一部分,而是DOM样式吗?如果是,还有什么替代方法吗?
Fiddle
可以在这里玩弄Fiddle。base64字符串已记录到控制台。
额外信息
Canvas是从svg
中创建的,使用的是https://code.google.com/p/canvg/
当使用HTML5的<canvas>
元素的.toDataURL()
方法时,元素的background-color
属性不会应用于图片。这是因为background-color
实际上不是canvas
的一部分,而是DOM样式吗?如果是,还有什么替代方法吗?
可以在这里玩弄Fiddle。base64字符串已记录到控制台。
Canvas是从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);
.drawSvg
有效,但对于canvg()
无效http://jsfiddle.net/qDmhV/159/。有什么想法为什么? - Artyom NeustroevingoreClear
更改为 ignoreClear
。 ;) - ZachRabbit希望这能有所帮助,
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();
.drawSvg
时运行良好,但使用canvg()
时没有成功。 - Artyom Neustroev