I am sending the content of a canvas to my API endpoint through ajax, and I would like to be able to wait for the response to come, before proceeding with the next function. My sending function looks like this:
function sendPicture(){
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var fd = new FormData();
fd.append('video', null);
var reso;
canvas.toBlob(function(blob){
fd.set('video', blob);
}, 'image/jpeg');
reso = $.ajax({
url: "/img",
type : "POST",
processData: false,
contentType: false,
data : fd,
dataType: "text",
});
return reso;
}
}
The function is already working when the ajax statement is used within the toBlob
callback, but doing so I do not have access anymore to the main scope in order to block the ajax promise.
From the current version of the function I think it would be enough if I managed to extract the blob
argument outside the callback scope, even though I would have expected that the fd.set('video', blob)
statement would have already set the formData object from the scope outside where it was initially created.
Does anyone have better suggestions? How can I convert the canvas to the blob without the method with the callback? Or better, how could I fill the formData of the outlying scope?