Rajesh Rs
Rajesh Rs

Reputation: 1391

How to write text on top of image in HTML5 canvas?

I want to display a image on canvas and insert a text on top of that image.

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

    imageObj.onload = function() {
        context.drawImage(imageObj, 10, 10);
    };

    imageObj.src = "darth-vader.jpg";
    context.font = "40pt Calibri";
    context.fillText("My TEXT!", 20, 20);
};

I'm getting only an image over here but not the text; the text is behind the image. How to insert the text on top of the image?

Upvotes: 30

Views: 69428

Answers (1)

Jonas
Jonas

Reputation: 129075

That is because you draw the text before the image has loaded and been drawn. You have to draw the text that should be on top of the image after the image is drawn. Try this code instead:

window.onload = function(){
     var canvas = document.getElementById("myCanvas");
     var context = canvas.getContext("2d");
     var imageObj = new Image();
     imageObj.onload = function(){
         context.drawImage(imageObj, 10, 10);
         context.font = "40pt Calibri";
         context.fillText("My TEXT!", 20, 20);
     };
     imageObj.src = "darth-vader.jpg"; 
};

Example:

enter image description here

Upvotes: 57

Related Questions