我找不到问题所在。我无法在画布上打印单词“ hello”,但似乎我的代码是合乎逻辑的。我尝试解决问题30分钟。
var words = ["buddha", "canoe", "dice", "elephant"];
var canvas;
var ctx;
//var timer;
var getrandomphoto = -1;
function play() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.font = "20px Arial";
ctx.fillStyle = "red";
ctx.fillText = ("hello", 100, 100);
// getrandomphoto= getrandomnumber();
// document.getElementById("hk").src= words[getrandomphoto]+".jpg" ;
}
function getrandomnumber() {
var random_num = Math.random() * words.length;
var random_int = Math.floor(random_num);
return random_int;
}
canvas {
border: 1px solid black;
}
#message {
color: red;
}
<img id="hk" src=".jpg" alt="no photo" width="200" /></img>
<br/>
<br/>
<canvas id="myCanvas" height="200" width="500"></canvas>
<br/>
<button onclick="play()">Play</button>
<button onclick="moveleft()">←</button>
<button onclick="moveright()">→</button>
<p id="message">Press Play</p>
<p>Plate X-coordinate: <span id="plateX"></span>
<p>Word X-coordinate: <span id="wordX"></span>
<p>Distance: <span id="dist"></span>
答案 0 :(得分:3)
您的问题是ctx.fillText
是一个函数,但是您没有使用任何参数调用它。因此,您需要使用参数来调用它,而不是将其设置为等于("hello", 100, 100)
:
ctx.fillText("hello", 100, 100);
请参见下面的工作示例:
<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
#message {
color: red;
}
</style>
<script>
var words = ["buddha", "canoe", "dice", "elephant"];
var canvas;
var ctx;
//var timer;
var getrandomphoto = -1;
function play() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
ctx.font = "20px Arial";
ctx.fillStyle = "red";
ctx.fillText("hello", 100, 100); // change ctx.fillText = ("hello", 100, 100) to ctx.fillText("hello", 100, 100)
getrandomphoto= getrandomnumber();
document.getElementById("hk").src= words[getrandomphoto]+".jpg" ;
}
function getrandomnumber() {
var random_num = Math.random() * words.length;
var random_int = Math.floor(random_num);
return random_int;
}
</script>
</head>
<body>
<img id="hk" src=".jpg" alt="no photo" width="200" /></img>
<br/>
<br/>
<canvas id="myCanvas" height="200" width="500"></canvas>
<br/>
<button onclick="play()">Play</button>
<button onclick="moveleft()">←</button>
<button onclick="moveright()">→</button>
<p id="message">Press Play</p>
<p>Plate X-coordinate: <span id="plateX"></span>
<p>Word X-coordinate: <span id="wordX"></span>
<p>Distance: <span id="dist"></span>
</body>
</html>