Javascript 如何在 HTML5 画布中的图像顶部写入文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8429011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:58:34  来源:igfitidea点击:

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

javascriptcanvastext

提问by Rajesh Rs

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?

我在这里只得到一个图像而不是文本;文字在图片后面。如何在图片上方插入文字?

回答by Jonas

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

在此处输入图片说明