Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  169] [ 1]  / answers: 1 / hits: 65850  / 13 Years ago, thu, december 8, 2011, 12:00:00

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?


More From » canvas

 Answers
2

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


[#88676] Wednesday, December 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
michaelashelbieh

Total Points: 303
Total Questions: 139
Total Answers: 97

Location: Suriname
Member since Sun, Oct 17, 2021
3 Years ago
michaelashelbieh questions
Sat, Nov 13, 21, 00:00, 3 Years ago
Fri, Sep 17, 21, 00:00, 3 Years ago
Tue, Sep 14, 21, 00:00, 3 Years ago
Mon, Aug 31, 20, 00:00, 4 Years ago
;