如何修复“ drawPlayer”(没有错误)

时间:2019-05-06 00:56:39

标签: javascript

我不知道我对这段代码做错了什么。

我已经尝试了重做整个脚本很多次,甚至将其重命名以查看它是否可以进行任何更改,但是并没有改变。

<!DOCTYPE html> 
<html>
<head> 
<title>Purely's Tower Defense</title>
<style> 
* { padding: 0; margin: 0; }
    canvas {background: #eee; display: block; margin: 0 auto}
 </style>
</head>
<body> 
 <canvas id="myCanvas" width='800' height='500'></canvas>
 <script type="text/javascript"> 
    var canvas = document.getElementById('myCanvas'); 
    var ctx = myCanvas.getContext('2d');
    var playerX = (canvas.width - playerWidth)/2;
    var playerY = canvas.height - playerHeight;
    var playerWidth = 30;
    var playerHeight = 30; 





function drawPlayer()
{
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(playerX, playerY, playerWidth, paddleHeight); 
ctx.closePath()
}


function draw()
{
ctx.clearRect(0,0,canvas.width,canvas.height);
drawPlayer(); 
}


draw();



</script>

</body>

</html>

我希望只有水晶和玩家才能产生。

1 个答案:

答案 0 :(得分:0)

您的代码中有两个独立的问题:

  1. 您正在基于playerXplayerY定义playerWidthplayerHeight
  2. 您在paddleHeight函数中使用的是playerHeight而不是drawPlayer

要解决此问题,您需要将变量声明顺序更改为在X和Y之前有playerWidthplayerHeight

var canvas = document.getElementById('myCanvas'); 
var ctx = myCanvas.getContext('2d');
var playerWidth = 30;
var playerHeight = 30;
var playerX = (canvas.width - playerWidth)/2;
var playerY = canvas.height - playerHeight; 

并更改您的drawPlayer函数以使用playerHeight

function drawPlayer()
{
  ctx.beginPath();
  ctx.fillStyle = "#000000";
  ctx.fillRect(playerX, playerY, playerWidth, playerHeight); 
  ctx.closePath();
}