简体   繁体   English

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

[英]add text on image using Javascript and Canvas

I have a question about this topic 我对此主题有疑问
How to add text on image using Javascript and Canvas 如何使用Javascript和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: 这是我来自php文件的代码:

<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: 这是我的js文件中的代码:

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

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 和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 在这里,我创建了一个可工作的JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM