Reputation: 25
Hello I am trying to put variable in text for context.fillText. Right now it shows 'undefined' on the screen. I want to show text in Canvas that user input. My code is:
<canvas id="myCanvas" width="578" height="200"></canvas>
<form>
<label for "text">Text:</label>
<input type="text" id="text">
<input type='submit' id="submit" value="submit" onClick="canvas_text()" >
</form>
<script>
var t, word;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
t = document.getElementById('text').value;
function canvas_text() {
if(t == '' || t == null) {
word = "you forgot to put something";
} else {
word = t;
}
}
context.font = '40pt Aria';
context.fillStyle = 'red';
context.fillText(word, 150, 100);
</script>
Upvotes: 0
Views: 4105
Reputation: 350
move this line:
context.fillText(word, 150, 100);
into the canvas_text function. As it currently is, it runs before the "text" variable has been defined.
Edit: this line has to be inside the function too:
t = document.getElementById('text').value;
Upvotes: 1