Get Image Data URL using JavaScript

It is very simple with HTML5 Canvas API, it provides toDataURL() method. The toDataURL() method of the canvas object converts the canvas drawing into a 64 bit encoded PNG URL. We can pass “image/jpeg” as argument to toDataURL() method, to get image data URL in the jpeg format.

Here is the code snippet which explains it:

  <title>Get Image Data URL using JavaScript</title>
      var image = new Image();

      // create an empty canvas element
      var canvas = document.createElement("canvas"),
          canvasContext = canvas.getContext("2d");

      image.onload = function () {
        //Set canvas size is same as the picture
        canvas.width = image.width;
        canvas.height = image.height;
        // draw image into canvas element
        canvasContext.drawImage(image, 0, 0, image.width, image.height);
        // get canvas contents as a data URL (returns png format by default)
        var dataURL = canvas.toDataURL();


      image.src = "azure.png";