dounabi6295 2018-12-19 16:31
浏览 1004

使用Javascript和Canvas在图像上添加文本

I have a question about this topic
How to add text on image using Javascript and Canvas

I am unable to get the image in the first go. But image load when I hit refresh.

This is my code from php file:

<canvas id="canvas"> </canvas>
<form class="myNameForm">
    <?php echo '<img style="display:none" class="myimage" 
        src="./save/'.$filenamewithoutExt.'" crossorigin="anonymous">';?>
    <label class="inpLable" for="input">Enter Name: </label>
    <input class="inp" maxlength="12" type="text" id="inp"/>
</form>

This is my code from js file:

window.onload = function() {
    var canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
    canvas.width = $('img').width();
    canvas.crossOrigin = "Anonymous";
    canvas.height = $('img').height();
    ctx.drawImage($('img').get(0), 0, 0);
    $(document).on('input', '#inp', function() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.font = "20pt Verdana";
        ctx.drawImage($('img').get(0), 0, 0);
        ctx.fillStyle = "white";
        ctx.fillText($(this).val(), 170, 590);
    });
};
  • 写回答

1条回答 默认 最新

  • dongshi9526 2018-12-19 17:23
    关注

    I have made small changes in your code

    <canvas id="canvas"> </canvas>
    <img style="display: none" class="myimage" src='https://picsum.photos/200/200'/>
    <label class="inpLable" for="input">Enter Name: </label>
    <input class="inp" maxlength="12" type="text" id="inp"/>
    

    And JS

    $('#inp').on('input', function(){
      var canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d');
      canvas.width = $('img').width();
      canvas.crossOrigin = "Anonymous";
      canvas.height = $('img').height();
      ctx.drawImage($('img').get(0), 0, 0);
      ctx.clearRect(0,0,canvas.width,canvas.height);
      ctx.font = "20px Verdana";
      ctx.drawImage($('img').get(0), 0, 0);
      ctx.fillStyle = "white";
      ctx.fillText($(this).val(), 10, 50);
    });
    

    Here I have created a working JSFiddle

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决