HTML5 canvas.toDataURL()图像没有背景色
HTML5 canvas .toDataURL() image has no background color
问题
当使用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();
相关文章:
- jquery.each(第2行)添加背景色
- 如果使用javascript函数屏幕太小,我该如何更改HTML文件的背景色
- 悬停时淡入背景色
- 如何在单击单元格中的链接值时动态更改表行背景色
- Gridview内部的下拉框在回发时未保留背景色
- 用背景色智能填充引导列
- 带有背景色的高图表柱形图
- 带有javascript的选定文本的背景色
- 当代码使用背景色时无法更改位置
- 将元素放置在方框顶部时更改方框的背景色
- 检索表中元素的背景色
- 在Wordpress中创建随机背景色
- 存在事件的单元格的jQuery DatePicker背景色(加载时)
- CSS转换未在增加高度时更新背景色
- 如何设置按钮来更改按钮的背景色
- 避免使用背景色和边框色
- 更改表列javascript的背景色
- 使用Jquery选中复选框时,更改复选框的背景色
- HTML5 canvas.toDataURL()图像没有背景色
- 通过单击图像更改CSS属性的背景色