28

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!

user1031947
  • 6,294
  • 16
  • 55
  • 88
  • 1
    possible duplicate of [How to convert a image from PNG to JPEG using javascript?](http://stackoverflow.com/questions/20744628/how-to-convert-a-image-from-png-to-jpeg-using-javascript) – Bohdan Lyzanets Aug 11 '15 at 08:29

2 Answers2

36

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

shakirthow
  • 1,356
  • 14
  • 15
19

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.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • Hey apsillers thank you for providing the answer for how to change the default background from black to transparent because I've been having problems with this for a while. – AaronG May 13 '18 at 23:22
  • funny enough, I didn't see this problem until I tried to load the image in a separate browser window - which apparently has a black background meaning the image only shows up as black when it's not part of a web page! – Michael Jun 12 '18 at 18:39