问题描述
我试图将canvas作为图片保存到firebase存储中。我已经阅读了很多关于将canvas保存到服务器的文章和问题,并试图用下面的代码实现它。function server(){
canvas = document.getElementById(c);
var storageRef = firebase.storage()。ref();
var mountainsRef = storageRef.child('mountains.jpg');
var image = new Image();
image.src = canvas.toDataURL(image / png);
var uploadTask = storageRef.child('images /'+apple)。put(image);
uploadTask.on('state_changed',function(snapshot){
//观察状态变化事件,如进度,暂停和恢复
//详见下面
},function(error){
//处理不成功的上传
},function(){
//完成
处理成功的上传//例如,获取下载URL :https://firebasestorage.googleapis.com / ...
var downloadURL = uploadTask.snapshot.downloadURL;
});
}
但是当我运行web应用程序时,控制台显示错误:
$ b
如何成功地将画布保存到Firebase存储设备?
是的,这是可能的。你遇到的问题是,你试图上传一个dataUrl,但firebase的put函数只有blob或文件除外。要将画布转换为blob,请使用 toBlob 函数。
canvas.toBlob(function(blob){
var image = new Image();
image .src = blob;
var uploadTask = storageRef.child('images /'+apple)。put(blob);
});
编辑:已更改 var uploadTask = storageRef.child('images /'+ apple)。put(image); to var uploadTask = storageRef.child('images /'+apple)。put(blob); $ c
也不知道这是否会在你的情况下工作,当我尝试它我得到了一个污点的画布错误。
I'm trying to save canvas as an image to the firebase storage. I have read many articles and questions about saving canvas to server, and tried to implement the same with the below code.
function server(){ canvas = document.getElementById("c"); var storageRef = firebase.storage().ref(); var mountainsRef = storageRef.child('mountains.jpg'); var image = new Image(); image.src = canvas.toDataURL("image/png"); var uploadTask = storageRef.child('images/' + "apple").put(image); uploadTask.on('state_changed', function(snapshot){ // Observe state change events such as progress, pause, and resume // See below for more detail }, function(error) { // Handle unsuccessful uploads }, function() { // Handle successful uploads on complete // For instance, get the download URL: https://firebasestorage.googleapis.com/... var downloadURL = uploadTask.snapshot.downloadURL; }); }
But when I run the web app, the console shows error:
How can I successfully save a canvas to Firebase storage?
Yes this is possible. The problem you are having is that you are trying to upload a dataUrl but firebase's put function only excepts blobs or files. To convert a canvas to a blob use the toBlob function.
canvas.toBlob(function(blob){ var image = new Image(); image.src = blob; var uploadTask = storageRef.child('images/' + "apple").put(blob); });
Edit: changed var uploadTask = storageRef.child('images/' + "apple").put(image); to var uploadTask = storageRef.child('images/' + "apple").put(blob);
Also not sure if this will work in your case when i tried it I got a tainted canvas error.
What worked for me was the answer to this question How to convert dataURL to file object in javascript?
这篇关于如何将画布保存为Firebase存储的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!