2017-06-15 2 views
0

Nun, schauen Sie sich diesen Code, vor allem auf ctx.rect() Funktion in drawPaddle Funktion und var paddleY.Zeichnen Rect() auf Leinwand mit Variablen - funktioniert nur mit Zahlen?

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title>GAME</title> 
 
\t <meta charset="utf-8"/> 
 
\t <style type="text/css"> 
 
\t \t canvas { 
 
\t \t \t background-color: gray; 
 
\t \t } 
 
\t </style> 
 
</head> 
 
<body> 
 
\t <canvas width="500" height="500" id="myCanvas"></canvas> 
 
\t 
 
\t <script type="text/javascript"> 
 
\t \t var canvas = document.getElementById('myCanvas'); \t 
 
\t \t var ctx = canvas.getContext('2d'); 
 

 
\t \t var ballX = canvas.width/2; 
 
\t \t var ballY = canvas.height - 80; 
 
\t \t var ballR = 10; 
 
\t \t var ballMX = 2; 
 
\t \t var ballMY = -2; 
 
\t \t var paddleX = (canvas.width/2) - (130/2); 
 
\t \t var paddleY = canvas.height - paddleH; 
 
\t \t var paddleW = 130; 
 
\t \t var paddleH = 15; 
 

 
\t \t function drawPaddle() { 
 
\t \t \t ctx.beginPath(); 
 
\t \t \t ctx.fillStyle = "green"; 
 
\t \t \t ctx.rect(paddleX, paddleY, paddleW, paddleH); 
 
\t \t \t ctx.fill(); 
 
\t \t \t ctx.closePath(); 
 
\t \t } 
 

 
\t \t drawPaddle(); 
 
\t </script> 
 
</body> 
 
</html>

in var paddleY bekam ich canvas.height - paddleH, diesen Code nicht Paddel ziehen, aber wenn ich in var paddleYcanvas.height - 15 es ändern funktioniert, warum es das ist?

Antwort

0

Betrachten Sie diesen Teil des Codes:

var paddleY = canvas.height - paddleH; 
var paddleW = 130; 
var paddleH = 15; 

Sie sind erst später paddleH definieren. Das heißt, in der ersten Zeile dieses Snippets wird paddleH in undefined aufgelöst und das Ergebnis ist keine Zahl. Das Rechteck kann nicht gezeichnet werden. Sie müssen paddleH vor der Berechnung paddleY initialisieren:

var paddleH = 15; 
var paddleY = canvas.height - paddleH; 

nun das Skript weiß, dass paddleH 15 ist und das Rechteck zeichnen.