Search code examples
html5-canvasdata-uri

Can I draw inline image on canvas?


I have the following code which renders an image as the background for a canvas:

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var destX = 69;
    var destY = 50;
    var imageObj = new Image();

    imageObj.onload = function(){
        context.drawImage(imageObj, destX, destY);
    };
    imageObj.src = "myImage.jpg";
};

What if now instead of an external file, I want to use an inline image as the background? For instance,

<img src="data:image/jpeg;base64,4uPk5ebn6Wql94XOr2gntJRE..." />

How can I make it the background for my canvas?

Edit: I found a tutorial (https://developer.mozilla.org/en/Canvas_tutorial/Using_images) which mentioned this, but there's no mention of how to use it.


Solution

  • If you want to write a image to 'canvas' then you should use drawImage api (that you are already doing).

    But if you want to put image to tag then you should convert the 'image file' to 'base64' uri. Usually it will be done by server side programming (PHP, Python) check here.