Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 604
Artyom Neustroev Avatar asked Sep 04 '13 09:09

Artyom Neustroev


People also ask

How do I get canvas toDataURL?

Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.

How do I get the base64 image from canvas?

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.

Is canvas toDataURL async?

Yes, images are loaded asynchronously by the browser.

What is canvas toDataURL?

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 .


2 Answers

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();
like image 165
Yash Avatar answered Oct 09 '22 20:10

Yash


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);
like image 12
ZachRabbit Avatar answered Oct 09 '22 21:10

ZachRabbit