canvas.toDataURL results in solid black image?

33,600

Solution 1

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

Solution 2

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.

Share:
33,600

Related videos on Youtube

user1031947
Author by

user1031947

Updated on November 05, 2020

Comments

  • user1031947
    user1031947 over 3 years

    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!

  • AaronG
    AaronG almost 6 years
    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.
  • Michael
    Michael almost 6 years
    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!