简体   繁体   中英

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?

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM