简体   繁体   English

canvas.toDataURL 导致纯黑色图像?

[英]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:我正在使用以下内容将画布转换为 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.但是,我得到的是纯黑色 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 .发生这种情况是因为 JPEG 不支持透明背景..如果您希望支持使用 png(默认扩展名),否则您可以使用 . fillStyle and . fillStyle和。 fillRect

Image created with a "image/jpeg" type have a default black background.使用"image/jpeg"类型创建的"image/jpeg"具有默认的黑色背景。 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.如果您只在画布上绘制了黑色形状,您将不会在默认的黑色 JPEG 背景下看到它们。

If you instead use the type image/png , the background will be transparent by default.如果您改为使用类型image/png ,默认情况下背景将是透明的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM