0

I have tried this code but it doesn't work out. Please tell errors(if any) or suggest a great and short code for displaying an image on canvas and then displaying text(by user input) over the image.

<html>
<body>
<form>
<input type="text" id="nm" placeholder="Name" value="some name">
<button onclick="ck()">Preview</button>
</form>
<canvas style="border:1px solid black;" height="500" width="700" id="can">          </canvas>
<script>
var can=document.getElementById('can').getcontext('2d');
function ck() {

    function def(){
        var img=new Image();
        can.font='40px algerian';
        img.src="form.jpg";
        img.onload=function() {
            can.drawImage(img,0,0,700,500);
            can.fillText("your name",400,200);
        };
    }

    function nondef() {
        var img=new Image();
        can.font='40px algerian';
        img.src="form.jpg";
        img.onload=function() {
            var nm=document.getElementById("nm").value;
            can.drawImage(img,0,0,700,500);
            can.fillText("nm",400,200);
        };

    }
    if(document.getElementById(nm).value=="")
        def();

    else
        nondef();
}
</script>
</body>
</html>
amphetamachine
  • 27,620
  • 12
  • 60
  • 72
Johny Gates
  • 75
  • 1
  • 9

2 Answers2

0

You need to declare the canvas context by adding this before the ck() function:

can = document.getElementById('can').getContext("2d");

Also, you should modify the form to prevent page reload:

<form action="javascript:void(0);">

Hope it helps!

htn
  • 301
  • 4
  • 8
  • what happens inside javascript which makes it lose variable's value if
    is not written??
    – Johny Gates Jun 12 '17 at 15:56
  • the default behaviour of the form is to submit that form, hence reload the page. The part action="javascript:void(0);" helps to prevent that default behaviour. There is other good stuff here for your reference: https://stackoverflow.com/questions/7803814/prevent-refresh-of-page-when-button-inside-form-clicked – htn Jun 13 '17 at 03:10
0

document.getElementById only picks up elements once the DOM has been fully constructed. You have to attach that to the document.onload handler:

window.document.onload = function (e) {
    window.can=document.getElementById('can').getcontext('2d');
}
amphetamachine
  • 27,620
  • 12
  • 60
  • 72