我对此主题有疑问
How to add text on image using Javascript and Canvas
我无法在第一时间获得图像。但是当我点击刷新时就会加载图片。
这是我来自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>
这是我的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);
});
};
答案 0 :(得分:0)
我对您的代码进行了小改动
<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"/>
还有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);
});
我在这里创建了一个有效的JSFiddle