Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would cause an HTML5 canvas toBlob to create an incomplete image?

I have the following javascript produce images from a canvas and upload them to a server.

var can = document.createElement('canvas');
can.width = 600;
can.height = 600;
var ctx = can.getContext('2d');
ctx.fillRect(0, 0, can.width, can.height);
ctx.fillText("Julia", can.width/2, can.height/2);
can.toBlob(uploadImage, "image/jpg", 0.9);

function uploadImage(jpeg) {
  var data = new FormData();
  data.append('image', jpeg, 'image.jpg');
  ...
}

enter image description here

Every so often, the result looks like the above, only partially drawn. Multiple canvases are processed and uploaded serially, only moving on in the completion of the ajax (in the ... part), so only one at a time.

Have you seen this happen? If so, where in this process should I debug further? Maybe a setting or something in the context object?

Edit

The upload is an ajax post with a promise resolved only on the success branch. It actually uses angular's $http service:

$http({method: 'POST', url: '...', data: data}).then(function(response) {
    // callback that processes and uploads the next image
});
like image 774
Ryan Calhoun Avatar asked Jun 01 '17 18:06

Ryan Calhoun


People also ask

What does canvas toBlob do?

toBlob() method creates a Blob object representing the image contained in the canvas. This file may be cached on the disk or stored in memory at the discretion of the user agent. The desired file format and image quality may be specified.

What is a Blob canvas?

Canvas to Blob is a polyfill for Browsers that don't support the standard JavaScript HTMLCanvasElement. toBlob method. It can be used to create Blob objects from an HTML canvas element.


1 Answers

We were facing with similar except part with canvas. You can debug it simply.

  1. Print given blob to page as img src to make sure that file was created properly. Print also blob size.
  2. Open browser's developer tools -> Network -> Filter XHR and start uploading
  3. Assign finished(status 200) ajax request and look at Request Headers -> Content-Length. If this number is equal to blob size on page, it was uploaded properly and find issue on server side. Else check ajax call.
  4. Make sure that server has set max client request size appropriate to your usecase. For example nginx has default value 1M.

TIP: set Content-Type by blob.type in $http headers. Default value for POST is application/json.

like image 52
bigless Avatar answered Oct 05 '22 16:10

bigless