我之前有变量“ballX”和“ballY”。但是,当我尝试使用console.log查看它们的值时,我现在必须搞砸了,因为它们现在显示为“未定义”。我花了最后2-3个小时查看我的代码和在线修复无济于事,任何帮助将不胜感激。(这是我第一次使用javascript,所以如果它是简单的事先道歉:))。< / p>
<html>
<canvas id="gameCanvas" width = "600" height = "250"></canvas>
<script>
//Calling technical stuff
var canvas;
var canvasContext;
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
// Initial values
var ballX = (canvas.width-20)/2;
var ballY = (canvas.height-20)/2;
var yDirection = 2;
var xDirection = 2;
var PositionY;
var drawEverythingCount = 0;
// Constants
var ballSize = 20;
var panelHeight = 100;
var panelWidth = 10;
window.onload = function(){
// Calls the main draw function and has the interval for repeating set to 10 ms
setInterval(function() {drawEverything(PositionY)}, 10);
}
//Adds the event for mousemove to record the Y position of the mouse
document.addEventListener("mousemove",function(event){
PositionY = (event.clientY-(panelHeight/2));
});
function drawEverything(PositionY) {
drawEverythingCount = drawEverythingCount + 1;
// Draws the canvas, ball and panel
canvasContext.fillStyle = 'black';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'red';
canvasContext.fillRect(ballX,ballY,ballSize,ballSize);
canvasContext.fillStyle = 'green';
canvasContext.fillRect(canvas.width-panelWidth,PositionY,panelWidth,panelHeight);
// Resets the game if the ball goes out of the Right side of the canvas
if (ballX > canvas.width) {
alert('You scored:' + (xDirection - 2) + '!')
var ballX = (canvas.width - 20)/2;
var ballY = (canvas.height-20)/2;
var yDirection = 2;
var xDirection = 2;
}
// Checks to see if the ball is about to hit the left-hand wall
if (ballX - xDirection < 0) {(xDirection = (xDirection*-1) + 1); ballX = 0;};
// Checks to see whether or not the ball is about to go off of the canvas' y-axis and changes its
// direction
if ((ballY+20) > canvas.height || ballY < 0){
if ((ballY+20) > canvas.height){yDirection = -1;} else {yDirection = 1;}
}
// Checks to see if the ball is hitting the panel
if ((ballX + xDirection) > (canvas.width - 10)){
var y
for (y = PositionY; y < (PositionY + 101);y++){
if(y == ballY) {xDirection = xDirection * -1;break;}
}};
// Movement of the ball
ballY = ballY + yDirection;
ballX = ballX + xDirection;
}
</script>
</html>
答案 0 :(得分:5)
在if (ballX > canvas.width)
声明中,您重新声明了变量,这就是它的混乱。这会将变量提升到函数drawEverything
的顶部,并隐藏在顶部作用域中声明的变量。在您的情况下,它将被声明为undefined
。
如果您删除变量前面的var
关键字,它将按预期工作,因为您将依赖变量的全局状态。
if (ballX > canvas.width) {
alert('You scored:' + (xDirection - 2) + '!')
ballX = (canvas.width - 20)/2;
ballY = (canvas.height-20)/2;
yDirection = 2;
xDirection = 2;
}
这是JavaScript提供的全局状态易用性的固有问题。但是,您可以采用一些技巧来缓解这些问题。使用let
和const
关键字会对您有很大的帮助。