使用Canvas向图像添加文本

时间:2016-02-22 20:38:05

标签: javascript html canvas text

我想创建一个小网站,以便在图片上添加文字。我添加了一个文本框和一个按钮以插入自定义文本,但它不起作用。我究竟做错了什么?提前致谢

<script>

function = function1(){
 var canvas = document.getElementById("myCanvas");
 var context = canvas.getContext("2d");
 var imageObj = new Image();

 t = document.getElementById('text').value;

 if(t == '' || t == null) {
 word = "you forgot to put something";
  } else {
 word = t;
 }

 };

  imageObj.onload = function(){
     context.drawImage(imageObj, 10, 10);
     context.font = "40pt Calibri";
     context.fillText(word, 20, 20);
 };
 imageObj.src = "img/image.jpg"; 
 };


 </script>

 <body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
 </body>

 <form>
    Text: <input id="textBox" placeholder="your text"/>
 <br>
     <input type='submit' id="submit" value="submit" onClick="function1()" >
 </form>

2 个答案:

答案 0 :(得分:1)

通过查看代码,看起来您正在尝试在加载图像之前绘制文本。

您必须先调用window.onload函数。

来自MDN

  

加载事件在文档加载过程结束时触发。此时,文档中的所有对象都在DOM中,并且所有图像,脚本,链接和子帧都已完成加载。

这是一个小例子。

&#13;
&#13;
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!", 50, 50);
     };
     imageObj.src = "http://cdn.playbuzz.com/cdn/503aeb8a-c1b8-4679-8ed3-da5e11643f29/8a940ebd-8630-4247-888e-c4c611f4f0e2.jpg"; 
};
&#13;
<canvas id="myCanvas"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您的代码中存在一些错误。

让我们先从HTML开始:

<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>

    <form id="myForm">
        Text: <input id="myText" placeholder="your text"/>
        <br />
        <input type="submit" value="submit" />
    </form>
</body>

然后是Javascript:

<script>
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var imageObj = new Image();

    imageObj.onload = function()
    {
        context.drawImage(imageObj, 0, 0);
    }  

    imageObj.src = "https://image.freepik.com/free-vector/abstract-background-in-geometric-style_1013-17.jpg"; 

    var myForm = document.getElementById('myForm');
    myForm.addEventListener('submit', function(e)
    {
        var text = document.getElementById('myText').value;

        if(text.lenght == 0)
        {
             alert("you forgot to put something");
        }

        context.font = "40pt Calibri";
        context.fillText(text, 50, 50);

        e.preventDefault();
    });

注意:您需要将脚本放在页面底部,就在</body>标记之前。