javascript HTML5 canvas .toDataURL() 图像没有背景色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18609715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 canvas .toDataURL() image has no background color
提问by Artyom Neustroev
Problem
问题
When using .toDataURL()
method of HTML5 <canvas>
element the background-color
property of the element is not applied to the picture.
使用.toDataURL()
HTML5<canvas>
元素的方法时,元素的background-color
属性不会应用于图片。
Question
问题
Is this happenning because background-color
is not actually a part of canvas
, but a DOM styling? If so, or anything else, what can be a workaround for this?
这是因为background-color
实际上不是 的一部分canvas
,而是 DOM 样式?如果是这样,或者其他任何事情,有什么办法可以解决这个问题?
Fiddle
小提琴
Fiddle to play with here. The base64 string is logged to console.
在这里玩小提琴。base64 字符串记录到控制台。
Additional info
附加信息
The canvas is created from the svg
using https://code.google.com/p/canvg/
画布是从svg
使用https://code.google.com/p/canvg/创建的
采纳答案by ZachRabbit
You're correct that it isn't actually a part of the image data, only a part of the styling. The easiest way around this is to just draw a rectangle before drawing the SVG:
你是对的,它实际上不是图像数据的一部分,只是样式的一部分。解决此问题的最简单方法是在绘制 SVG 之前绘制一个矩形:
var canvas = document.getElementById('test');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, canvas.width, canvas.height);
回答by Yash
Other approach could be creating a dummy CANVAS and copying the original CANVAS content onto it.
其他方法可能是创建一个虚拟 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();
回答by SamithC
hope this will help,
希望这会有所帮助,
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();