简体   繁体   中英

HTML5 canvas .toDataURL() image has no background color

Problem

When using .toDataURL() method of HTML5 <canvas> element the background-color property of the element is not applied to the picture.

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?

Fiddle

Fiddle to play with here . The base64 string is logged to console.

Additional info

The canvas is created from the svg using https://code.google.com/p/canvg/

Other approach could be creating a dummy CANVAS and copying the original CANVAS content onto it.

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

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM