Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
Rajesh Rs Avatar asked Dec 08 '11 09:12

Rajesh Rs


People also ask

How do I put text on top of an image in HTML?

CSS position property is used to set the position of text over an image. This can be done by enclosing the image and text in an HTML “div”. Then make the position of div “relative” and that of text “absolute”.

How do you put text on a picture in canvas?

Go to the Text pane on the left sidebar. Select from hundreds of pre-formatted text holders. Or add your own text box by keying T on the editor. Then, add your desired text.


1 Answers

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

like image 54
Jonas Avatar answered Oct 06 '22 14:10

Jonas