stud91
stud91

Reputation: 1854

HTML5 Canvas text not appearing

I am trying to display a text on a canvas by entering a message in a textbox but it's not appearing.

Here is my code:

<html>
    <body>
        <canvas id="myCanvas" width="600" height="400"></canvas>
        <input type="text" name="fname" size="50" id="form_val">
        <button onclick="clicked()">Submit</button>

        <script type="text/javascript">
            function clicked () {
                var x = document.getElementById("form_val");
                return x.value;
            }

            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
            ctx.font = "25px Verdana";
            ctx.fillText(clicked(), 250, 250);
        </script>       
    </body>
</html>

Upvotes: 2

Views: 4395

Answers (3)

net.uk.sweet
net.uk.sweet

Reputation: 12431

HTML:

<canvas id="myCanvas" width="600" height="400"></canvas>

<input type="text" name="fname" size="50" id="form_val">
<button id='submit'>Submit</button>

JavaScript:

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");
ctx.font="25px Verdana";

document.getElementById('submit').addEventListener('click', clicked);

function clicked(){
 var x=document.getElementById("form_val");
 // Create the text when the button is clicked
 ctx.fillText(x.value,250,250);
}

Fiddle.

Upvotes: 1

pollirrata
pollirrata

Reputation: 5286

I believe you want to do something like this

<script type="text/javascript">
function clicked(){
 var x=document.getElementById("form_val");

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="25px Verdana";
ctx.fillText(x.value,250,250);
}

With this, the text will be filled when clicking the button. Note: I haven't tested the code, but you might get the picture

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22395

The code outside of your function is triggered immediately, put it inside the function so it's called when it needs to be (as it currently stands, it calls nothing. And when you click the button, it's returning the input value to the onclick method. Try this instead:

function clicked(){
   var x=document.getElementById("form_val");
   var c=document.getElementById("myCanvas");
   var ctx=c.getContext("2d");
   ctx.font="25px Verdana";
   ctx.fillText(x.value,250,250);
}

Upvotes: 6

Related Questions