Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas.toDataURL results in solid black image?

I have a canvas element with some doodling in it.

I am using the following to convert the canvas to a jpeg:

var data = canvas.toDataURL( "image/jpeg", 0.5 );
var img = new Image();
img.src = data;
$( "body" ).append( img );

However instead of my doodle, I get a solid black jpeg.

Can anyone tell me what I'm doing wrong?

Thanks!

like image 537
user1031947 Avatar asked Nov 04 '14 18:11

user1031947


People also ask

Why is my canvas background Black?

This blackening occurs because the 'image/jpeg' conversion involves setting the alpha of all canvas pixels to fully opaque (alpha=255). The problem is that transparent canvas pixels are colored fully-black-but-transparent . So when you turn these black pixels opaque, the result is a blackened jpeg.

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

Thats happening because the JPEG does not support a transparent background.. if you want that to be supported use png (the default extension) else you can set a non transparent fill color to the canvas using .fillStyle and .fillRect

like image 64
shakirthow Avatar answered Oct 19 '22 01:10

shakirthow


Image created with a "image/jpeg" type have a default black background. Consider the snippet below in which the canvas is on the left and the captured image is on the right:

var canvas = $("#c").get(0), ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect(40,60,20,20);

var data = canvas.toDataURL("image/jpeg");
var img = new Image();
img.src = data;
$( "body" ).append( img );

var data = canvas.toDataURL("image/png");
var img = new Image();
img.src = data;
$( "body" ).append( img );
canvas { border: thin solid green; }
img { border: thin solid black; margin-right: 5px; }
body { background-color: #DFF; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c" width="100"></canvas>

If you've only drawn black shapes on the canvas, you won't see them against a default black JPEG background.

If you instead use the type image/png, the background will be transparent by default.

like image 30
apsillers Avatar answered Oct 19 '22 01:10

apsillers