好的,请查看此代码,主要是ctx.rect()
函数和drawPaddle
中的var paddleY
函数。
<!DOCTYPE html>
<html>
<head>
<title>GAME</title>
<meta charset="utf-8"/>
<style type="text/css">
canvas {
background-color: gray;
}
</style>
</head>
<body>
<canvas width="500" height="500" id="myCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var ballX = canvas.width / 2;
var ballY = canvas.height - 80;
var ballR = 10;
var ballMX = 2;
var ballMY = -2;
var paddleX = (canvas.width / 2) - (130 / 2);
var paddleY = canvas.height - paddleH;
var paddleW = 130;
var paddleH = 15;
function drawPaddle() {
ctx.beginPath();
ctx.fillStyle = "green";
ctx.rect(paddleX, paddleY, paddleW, paddleH);
ctx.fill();
ctx.closePath();
}
drawPaddle();
</script>
</body>
</html>
在var paddleY
我得到了canvas.height - paddleH
,这段代码没有绘制划线,但是当我更改var paddleY
canvas.height - 15
时,它的工作原理是什么?
答案 0 :(得分:0)
考虑这部分代码:
var paddleY = canvas.height - paddleH;
var paddleW = 130;
var paddleH = 15;
您之后才会定义paddleH。这意味着,在此代码段的第一行,paddleH
会解析为undefined
,因此结果不是数字,无法绘制矩形。您需要在计算paddleY之前初始化paddleH
:
var paddleH = 15;
var paddleY = canvas.height - paddleH;
现在脚本知道paddleH
是15并且可以绘制矩形。