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!
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
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.