您好我正在尝试将变量放在context.fillText的文本中。现在它显示' undefined'屏幕上。我想在Canvas中显示用户输入的文本。 我的代码是:
<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>
答案 0 :(得分:0)
移动这一行:
context.fillText(word, 150, 100);
进入canvas_text函数。就目前而言,它在&#34;文本&#34;之前运行。已经定义了变量。
编辑:这一行也必须在函数内部:
t = document.getElementById('text').value;