如何在HTML5 canvas中的图像之上写文本? [英] How to write the text on top of image in HTML5 canvas?

查看:722
本文介绍了如何在HTML5 canvas中的图像之上写文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在画布上显示图片,并在图片顶部插入文字。

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

   <script>
      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);
  };


  </script>

只有一个图像在这里而不是文本,文本是图像的后面。
如何在图像顶部插入文本?

Im 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"; 
};

示例:

这篇关于如何在HTML5 canvas中的图像之上写文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆