When using .toDataURL()
method of HTML5 <canvas>
element the background-color
property of the element is not applied to the picture.
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 to play with here. The base64 string is logged to console.
The canvas is created from the svg
using https://code.google.com/p/canvg/
Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.
The canvas in HTML5 has a method called toDataURL() that you can call to turn a HTML5 canvas into a PNG image and to get the image data of that canvas. By default it will give you a base64 representation of the image in PNG format. In simpler terms, you will get a PNG image but it has been encoded in base64.
Yes, images are loaded asynchronously by the browser.
toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With