Learn more about the new method

The canvas element is getting an upgrade with the upcoming Chrome 50: it now supports the toBlob() method.

This is great news for anyone generating images on the client side, upload them to their server, or store them in IndexedDB for future use.

Using toBlob() is great upgrade, because instead of manipulating a base64 encoded string that you get from toDataURL(), you can now you work with the encoded binary data directly. It’s smaller, and it "tends to fit more use-cases" than a data URI.

You can event draw image blobs to another canvas context using the createImageBitmap API which will come too for Chrome 50.

How to use

The toBlob method is asynchronous, therefore expects a function as first parameter. This function receives as first parameter the blob element :

<canvas id="canvas"  width="200" height="200" style="border:1px solid #000000;"><input type="button" value="Send Image to server" id="send"/>

<script>
function imageToServer(canvas, url) {

  function onBlob (blob) {
    var request = new XMLHttpRequest();
    request.open('POST', url);
    request.onload = function (evt) {
      // Blob sent to server.
    }

    request.send(blob);
  }

  canvas.toBlob(onBlob);
}

window.onload = function(){
  document.getElementById("send").addEventListener("click",function(){
      var canvas = document.getElementById("canvas");
      imageToServer(canvas,"/a-service-to-process-the-image");
  },false);
};

</script>

The previous code will generate a image blob that will be sent to a url service that will process the blob.

Important: You can test this feature with Chrome Canary as the latest chrome version is 49 till the date and this feature will be only available for Chrome 50.


Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Become a more social person

Sponsors