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

Art*_*oev 11 javascript html5 canvas

问题

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

这是否发生,因为background-color它实际上不是一部分canvas,而是DOM样式?如果是这样,或者其他什么,可以解决这个问题的方法是什么?

小提琴

摆弄在这里玩.base64字符串将记录到控制台.

附加信息

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

Yas*_*ash 29

其他方法可能是创建一个虚拟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();
Run Code Online (Sandbox Code Playgroud)

  • 这应该是正确的答案...正在努力寻找如此美丽的答案...早期的答案使整个图像变白。做得好!!! (2认同)

Zac*_*bit 10

你是正确的,它实际上不是图像数据的一部分,只是造型的一部分.最简单的方法是在绘制SVG之前绘制一个矩形:

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

  • 尝试将`ingoreClear`更改为`ignoreClear`.;) (2认同)