Javascript canvas.toDataURL 导致纯黑色图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26742180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
canvas.toDataURL results in solid black image?
提问by user1031947
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!
谢谢!
回答by shakirthow
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 .fillStyleand .fillRect
发生这种情况是因为 JPEG 不支持透明背景..如果您希望支持使用 png(默认扩展名),否则您可以使用 . fillStyle和 。fillRect
回答by apsillers
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:
使用"image/jpeg"类型创建的图像具有默认的黑色背景。考虑下面的片段,其中画布在左侧,捕获的图像在右侧:
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.
如果您改为使用 type image/png,默认情况下背景将是透明的。

