如何在HTML5画布上的图像顶部撰写文字? [英] How to write text on top of image in HTML5 canvas?

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

问题描述

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

我只在这里获得一张图片,但不是文字;文字在图像后面。
如何在图片上插入文字?

解决方案

这是因为您在图片之前绘制了文字已加载并被绘制。绘制图像后,您必须绘制图像顶部的文字。请尝试以下代码:

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

示例:


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:

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

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