0

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);
    });
};
James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

2

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

Mirakurun
  • 4,859
  • 5
  • 16
  • 32
  • But the image load when the user starts typing. I want the image to load when page loads. not when user starts typing. – Usman Ahmed Mani Dec 19 '18 at 17:27
  • So you want the image only to show after a refresh, but show what was typed before the refresh? Canvases are cleared when the page unloads, which includes during a refresh. So you'll have to store the user input somehow (either server-side, or locally with session storage or local storage or something similar), and then load the text from there on page load and re-create the canvas image. – IceMetalPunk Dec 20 '18 at 15:31