Drawing an image from a data URL to a canvas

218,299

Solution 1

Given a data URL, you can create an image (either on the page or purely in JS) by setting the src of the image to your data URL. For example:

var img = new Image;
img.src = strDataURI;

The drawImage() method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.

You might use it like so:

var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
  ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;

Edit: I previously suggested in this space that it might not be necessary to use the onload handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload to use the new image, and then set the src—is necessary for some browsers to surely use the results.

Solution 2

function drawDataURIOnCanvas(strDataURI, canvas) {
    "use strict";
    var img = new window.Image();
    img.addEventListener("load", function () {
        canvas.getContext("2d").drawImage(img, 0, 0);
    });
    img.setAttribute("src", strDataURI);
}

Solution 3

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

Solution 4

Mixing the answers I do.

function drawDataURIOnCanvas(strDataURI, canvas) {
   var img = new window.Image();
   img.addEventListener("load", function () {
     canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
     canvas.width = img.width;
     canvas.height = img.height;
     canvas.getContext("2d").drawImage(img, 0, 0, img.width, img.height);
   });

   img.setAttribute("src", strDataURI);
}

Solution 5

You might wanna clear the old Image before setting a new Image.

You also need to update the Canvas size for a new Image.

This is how I am doing in my project:

    // on image load update Canvas Image 
    this.image.onload = () => {

      // Clear Old Image and Reset Bounds
      canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.canvas.height = this.image.height;
      this.canvas.width = this.image.width;

      // Redraw Image
      canvasContext.drawImage(
        this.image,
        0,
        0,
        this.image.width,
        this.image.height
      );
    };
Share:
218,299
Yahoo
Author by

Yahoo

Updated on April 05, 2021

Comments

  • Yahoo
    Yahoo about 3 years

    How can i open an image in a Canvas ? which is encoded

    I am using the

    var strDataURI = oCanvas.toDataURL(); 
    

    The output is the encoded base 64 image. How can i draw this image on a canvas?

    I want to use the strDataURI and create the Image ? Is it poosible ?
    If its not then what possibly can be the solution for loading the image on a canvas ?

  • Phrogz
    Phrogz over 13 years
    This does not answer the OP's question related to the dataURL.
  • Juho Vepsäläinen
    Juho Vepsäläinen over 13 years
    Using onload handler is definitely a good idea. It might take a while to load the image so it's better to play it safe. :)
  • Phrogz
    Phrogz over 13 years
    @bebraw Let's see about that for sure: stackoverflow.com/questions/4776670/… :)
  • Jepser Bernardino
    Jepser Bernardino over 12 years
    @Phrogz it gives me an error: var ctx = myCanvas.getContext('2d'); just copy/past your code to test
  • Phrogz
    Phrogz over 12 years
    @jepser Do you have a canvas element on your page with that id? Have you ensured that myCanvas is not null? If you still have trouble, post your own question, or come to the JavaScript chat channel.
  • Phrogz
    Phrogz over 11 years
    @DavidMurdoch Great information. Do you have a Chromium bug that you could link to, so that users will know when the above statement is no longer true?
  • Alston
    Alston over 11 years
    @Phrogz I tried several times on the Android Browser and Chrome, it can't work.
  • Scott
    Scott over 10 years
    Why would you use jQuery to select the canvas? Is typing document.getElementById() too much work?
  • Mohammad Ashfaq
    Mohammad Ashfaq almost 10 years
    This code works, though it is not related to question
  • Phrogz
    Phrogz almost 7 years
    @arqam 1. You are drawing to a canvas that you create and never show, so we would never see it working in that fiddle. 2. When you load an image from another domain and draw it to your canvas, it "taints" the canvas such that you can no longer access the data (either via data URL of imageData).
  • Konstantinos Monachopoulos
    Konstantinos Monachopoulos over 4 years
    Doesn't work. Still getting blank canvas, even after img.src = strDataURI; ...
  • Ulf Aslak
    Ulf Aslak over 2 years
    AAAh THANK you for this! I wanted to put a PNG onto a canvas inside a function, but it returned before the img.onload function had run. Using await solved that.