One variable is breaking my simple program, why? - javascript

I'm following a tutorial and trying to modify some code. As the code currently stands, everything is in working order to have a ball bounce around a square and off a paddle at the bottom and all I want to do is make the ball bigger when it bounces off the paddle. The balls starts at size 15 and I can increment it by 1-4 but at 5 and beyond, there is a bug that causes the ball to stay in location and grow to half the screen and then just stay there. I think as it grows it clips back into the hitbox for the paddle and then activates another growth and repeat. However, I am totally unsure. Can anyone shed some light? I will put a capitalized comment on the variable responsible halfway down the code. Thank you very much for any assistance!
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2; //starting coordinates
var y = canvas.height - 30;
var dx = 2; //rate of movement for ball
var dy = -2;
var ballRadius = 15;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#ff0000";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
x += dx;
y += dy;
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { //these ifs cause the ball to bounce off walls
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) { //detects paddlebox detection
dy = -dy;
ballRadius += 7; //TROUBLESOME VARIABLE! Work with 1-4 but breaks beyond that.
} else {
alert("GAME OVER");
document.location.reload();
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
}
}
setInterval(draw, 10);
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>

The issue was that your draw function excecutes every 10ms. So when your ball hits the paddle it actually triggers the ball to grow multiple number of times. My solution was to how a timeout/delay when you increase the size of the ball so that it has time to move away before the next time the draw function fires. Heres the code.
NOTE : Open up the snippet in full screen to view the game better
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2; //starting coordinates
var y = canvas.height - 30;
var dx = 2; //rate of movement for ball
var dy = -2;
var ballRadius = 15;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width - paddleWidth) / 2;
var rightPressed = false;
var leftPressed = false;
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#ff0000";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
x += dx;
y += dy;
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { //these ifs cause the ball to bounce off walls
dx = -dx;
}
if (y + dy < ballRadius) {
dy = -dy;
} else if (y + dy > canvas.height - ballRadius) {
if (x > paddleX && x < paddleX + paddleWidth) { //detects paddlebox detection
dy = -dy;
setTimeout(function(){ ballRadius += 7; }, 100);
} else {
alert("GAME OVER");
document.location.reload();
}
}
if (rightPressed && paddleX < canvas.width - paddleWidth) {
paddleX += 7;
} else if (leftPressed && paddleX > 0) {
paddleX -= 7;
}
}
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 39) {
rightPressed = true;
} else if (e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 39) {
rightPressed = false;
} else if (e.keyCode == 37) {
leftPressed = false;
}
}
setInterval(draw, 10);
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>

Related

Game doesn't work, but my code looks fine

I've been following an online tutorial for making a Breakout Game using JS, but it doesn't work. Even something as simple as an alert popup doesn't work. All of this started happening after I created the keyboard controls, and all of the errors are in that section as well. But it looks fine, i've compared the sample code with mine and everything's identical. What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background:rgba(104, 10, 93, 0.61);
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
</body>
<script>
// JS goes here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUphandler, false);
alert('test')
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
}
elseif(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.key -- "Right" || e.key == "ArrowRight") {
rightPressed = false;
}
elseif(e.key-- "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#EE82EE";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleheight, paddleWidth, paddleHeight);
ctx.fillStyle = "#9400D3";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightPressed) {
paddleX += 7;
if (paddleX + paddleWidth > canvas.width){
paddleX = canvas.width - paddleWidth;
}
}
else if(leftPressed) {
paddleX -= 7;
if (paddleX < 0){
paddleX = 0;
}
x += dx;
y += dy;
}
}
setInterval(draw, 10);
</script>
</body>
</html>
You have numerous typos in your code. This version should work better (at least it does not generate any errors):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background:rgba(104, 10, 93, 0.61);
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
</body>
<script>
// JS goes here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
alert('test')
function keyDownHandler(e) {
if(e.key == "Right" || e.key == "ArrowRight") {
rightPressed = true;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = true;
}
}
function keyUpHandler(e) {
if (e.key == "Right" || e.key == "ArrowRight") {
rightPressed = false;
}
else if(e.key == "Left" || e.key == "ArrowLeft") {
leftPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#EE82EE";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#9400D3";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
if(x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if (rightPressed) {
paddleX += 7;
if (paddleX + paddleWidth > canvas.width){
paddleX = canvas.width - paddleWidth;
}
}
else if(leftPressed) {
paddleX -= 7;
if (paddleX < 0){
paddleX = 0;
}
x += dx;
y += dy;
}
}
setInterval(draw, 10);
</script>
</html>

How do you move a drawing in javascript up down right and left

I was wondering how to move the red ball right and left (I already did, but its not working) and also how to move it up and down.
<canvas id="canvas" width="480" height="320"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var ball;
var obstacle;
var x = canvas.width / 2;
var y = canvas.height / 2;
var dx = 2;
var dy = -2;
var redballRadius = 10;
var ballRadius = 20;
var rightpressed = false;
var leftpressed = false;
var ballX = (canvas.width - redballDiameter) / 2;
var redballDiameter = redballRadius * 2;
function startGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ball = new drawBall(30, 30, 'red', 20, 10);
obstacle = new drawObstacle(40, 30, 'blue', 15, 10);
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius) {
dy = -dy;
}
if(rightpressed && ballX < canvas.width-redballDiameter) {
ballX += 7;
}
else if(leftpressed && ballX > 0) {
ballX -= 7;
}
}
//keyboard controls
document.addEventListener('keydown', keyDownHandler, false);
document.addEventListener('keyup', keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightpressed = true;
}
else if(e.keyCode == 37) {
leftpressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightpressed = false;
}
else if (e.keyCode == 37) {
leftpressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(30, 30, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
function drawObstacle() {
x += dx;
y += dy;
ctx.beginPath();
ctx.arc(x, y, 20, 10, 1 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
}
setInterval(startGame, 10);
I am basically wondering how to move it up down right and left with the keys. Thanks
I took a look at your code. In your life cycle, you are calling drawBall, now sure what you are trying to do with the new there. anyways, I updated the function to use the ballX your key handling logic updates.
function drawBall() {
ctx.beginPath();
ctx.arc(ballX, 30, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
here is the working code pen. http://codepen.io/poda/pen/aNPPEp
move a ball to up, down, right and left.
it would be better to use object than use global variable of x_pos and y_pos of ball
function drawBall() {
this.ball_x = 30;
this.ball_y = 30;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.ball_x, this.ball_y, 15, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
},
this.move = function() {
if(rightpressed && this.ball_x < canvas.width-redballDiameter) {
this.ball_x += 5;
}
else if(leftpressed && this.ball_x > redballDiameter) {
this.ball_x -= 5;
}
else if(uppressed && this.ball_y > redballDiameter) {
this.ball_y -= 5;
}
else if(downpressed && this.ball_y < canvas.height - redballDiameter) {
this.ball_y += 5;
}
},
this.collision = function() {
//stuff
}
}
Here's a fiddle

Unable to draw to canvas

I have a project where I have to create a block breaking game in canvas, but for some reason the code has stopped drawing in the canvas and I haven't been able to find a solution to the problem.
//global variable
//setting the canvas state
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Boolean variables for each stage of the game
var startscreen = true;
var gameplaying = false;
var Game_over = false;
//Setting the ball position and size
var ball_x = canvas.width / 2;
var ball_y = canvas.height - 30;
var ballRadius = 5;
//Setting the ball movement
var dx = 2;
var dy = -2;
//PLayer paddle size
var p_height = 10;
var p_width = 100;
//Player paddle start position
var Paddlex = (canvas.width - p_width) / 2;
var Paddley = canvas.height - p_height;
//making sure the paddle doesnt move on its own
var paddleright = false;
var paddleleft = false;
//Set up the target blocks
var brickRowCount = 5;
var brickColumnCount = 13;
var brickWidth = 24;
var brickHeight = 20;
var brickPadding = 10;
var brickOffsetTop = 30;
var brickOffsetLeft = 30;
var rowColours = ["#2294B2", "#FF3175", "#17CEFF", "#CCBF27", "#B2A507"];
var bricks = [];
for (c = 0; c < brickColumnCount; c++) {
bricks[c] = [];
for (r = 0; r < brickRowCount; r++) {
bricks[c][r] = {
x: 0,
y: 0,
status: 1
};
}
}
//setting the event listeners to detect keypresses
document.addEventListener("Keydown", keyDownHandler, false);
document.addEventListener("Keyup", keyUpHandler, false);
//Detecting the key press
function keyDownHandler(e) {
if (e.keyCode == 39) {
paddleright = true;
}
if (e.keyCode == 37) {
paddleleft = true;
}
}
//Detecting the Key press has stopped
function keyUpHandler(e) {
if (e.keyCode == 39) {
paddleright = false;
}
if (e.keyCode == 37) {
paddleleft = false;
} else if (e.keyCode == 13) {
startscreen = false;
gameplaying = true;
Game_over = false;
}
}
//drawing the ball
function ball() {
ctx.beginPath();
ctx.arc(ball_x, ball_y, ballRadius, 0, Math.pi * 2);
ctx.fillstyle = "red";
ctx.fill();
ctx.closePath();
}
//drawing player paddle
function paddle() {
ctx.beginPath();
ctx.rect(Paddlex, Paddley, p_width, p_height);
ctx.fillstyle = "green";
ctx.fill();
ctx.closePath();
}
//Drawing the blocks
function drawBricks() {
for (c = 0; c < brickColumnCount; c++) {
for (r = 0; r < brickRowCount; r++) {
ctx.fillstyle = rowColours[r];
if (bricks[c][r].status === 1) {
var brickX = (c * (brickWidth + brickPadding)) + brickOffsetLeft;
var brickY = (r * (brickHeight + brickPadding)) + brickOffsetTop;
bricks[c][r].x = brickX;
bricks[c][r].y = brickY;
ctx.beginPath();
ctx.rect(brickX, brickY, brickWidth, brickHeight);
ctx.fill();
ctx.closePath();
}
}
}
}
//drawing the above functions to the screen
function draw() {
//Startscreen and main menu
if (startscreen) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//Set background colour
var gradient = ctx.createLinearGradient(0, 0, 170, 0);
gradient.addcolorstop(0, 'blue');
gradient.addcolorstop(0, 'orange');
ctx.fillstyle = gradient;
ctx.fillRect(0, 0, 500, 500);
//Welcome title
ctx.font = '20px verdana';
ctx.fillstyle = "white";
ctx.fillText("Block Breaker", 50, 50);
//Welcome tagline
ctx.fillText("Break some blocks", 50, 100);
//Rules of play text
ctx.fillText("How to play:", 80, 200);
ctx.fillText("To play, move the paddle", 80, 280);
ctx.fillText("with the left and right arrow keys", 80, 310);
ctx.fillText("Press ENTER to begin.", 80, 250);
// Call key up function
keyUpHandler();
}
//Game play
if (gameplaying) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//calling the ball, paddle and blocks in the draw function
ball();
paddle();
drawBricks();
//bounce off the walls
if (ball_x + dx > canvas.width - ballRadius || ball_x + dx < ballRadius) {
console.log("Ball bounced off the side");
sx = -dx;
}
//if the ball hits the top
if (ball_y + dy < ballRadius) {
console.log("Ball bounced off the top");
}
//If the ball hits the bottom
if (ball_y + dy > canvas.height - ballRadius) {
//If the ball hits the player1 paddle
if (ball_y + dy > Paddley && ball_x > Paddlex && ball_x < Paddlex + p_width) {
console.log("Ball hit the player paddle");
dy = -dy;
}
//the ball hits the base
else if (ball_y + dy > canvas.height) {
console.log("Ball hit the bottom of the screen");
gameplaying = false;
Game_over = true;
}
}
}
//Gameover screen
if (Game_over) {
var gradient = ctx.createLinearGradient(0, 0, 0, 170);
gradient.addcolorstop(0, "blue");
gradient.addcolorstop(0, "orange");
ctx.fillstyle = gradient;
ctx.fillRect(0, 0, 500, 500);
//Welcome title
ctx.font = '20px verdana';
ctx.fillstyle = "white";
ctx.fillText("Game Over", 50, 50);
//Main Text body
ctx.fillText("Press Enter to return tot the main menu", 80, 200);
//Reload the game
function keyUpHandler(e) {
if (e.keyCode == 13) {
startscreen = true;
Game_over = false;
}
}
}
//If the ball hits a block
if (ball_x)
//Movement speed of the paddle
if (paddleright && Paddlex < canvas.width - p_width) {
Paddlex += 5;
} else if (paddleleft && Paddlex > 0) {
Paddlex -= 5;
}
ball_x += dx;
ball_y += dy;
//Setting the framerate
setInterval(draw, 10);
}
<canvas id="canvas"></canvas>
move the following line down two lines (so it is not inside draw())
setInterval(draw, 10);
Also, I would strongly encourage you to change 10 to (1000 / FPS), where FPS is frames per second. You probably won't be able to finish executing draw() within 10ms thus creating a drag on the CPU

How to make the ball move faster when it hits paddle?

How to make the ball move faster when it hits paddle !
var canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d");
var dx = 2;var dy = -2;
var w = canvas.width, h = canvas.height;
var x = w/2;var y = h-30;
var ballRadius = 10;
var color = getColor();
var paddleHeight = 10;var paddleWidth = 75;var paddleX = (w-paddleWidth)/2;
var rightPressed = false;
var leftPressed = false;
document.addEventListener("keydown", keyDownHandler,false);
document.addEventListener("keyup", keyUpHandler,false);
function keyDownHandler(e) {
if(e.keyCode == 39) {
rightPressed = true;
}
else if(e.keyCode == 37) {
leftPressed = true;
}
}
function keyUpHandler(e) {
if(e.keyCode == 39) {
rightPressed = false;
}
else if(e.keyCode == 37) {
leftPressed = false;
}
}
function getColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, h-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#eee";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0,0,w,h);
drawBall();
drawPaddle();
if(x + dx < ballRadius || x + dx > w-ballRadius) {
dx = -dx;
color = getColor();
}
if(y + dy < ballRadius) {
dy = -dy;
color = getColor();
}else if(y + dy > h-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy;
}
else {
alert("GAME OVER");
}
}
if(rightPressed && paddleX < w-paddleWidth) {
paddleX += 7;
}
else if(leftPressed && paddleX > 0) {
paddleX -= 7;
}
x += dx;
y += dy;
}
setInterval(draw, 10);
/*left arrow: 37
up arrow: 38
right arrow: 39
down arrow: 40*/
* {
background-color: #224;
padding: 0; margin: 0;
}
canvas {
background: #555;
display: block;
margin: 10px auto;
}
<canvas id="myCanvas" width="480px" height="320px"></canvas>
Modify the bounce code in the draw function:
if(y + dy < ballRadius) {
dy = -dy;
color = getColor();
}
else if(y + dy > h-ballRadius) {
if(x > paddleX && x < paddleX + paddleWidth) {
dy = -dy * 1.1;
}
Note the last line:
dy = -dy * 1.1;
This means that dy will be increased by 10% each time the paddle hits the ball. You could change 1.1 to modify the scaling factor.

My HTML game is not running, what's wrong?

I wrote this game from a tutorial i read online, it was working just fine, until i messed it up, my developer tools console says theres a reference error but i just cant see it, please help, the error i get through my we developer console is "Uncaught ReferenceError: Draw is not defined(anonymous function) # games.html:228 "
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Gamedev Canvas Workshop</title>
<style>
* { padding: 0; margin: 0; }
canvas { background: #eee;
display: block;
margin: 0 auto;
}
#checking {
margin-left:650px;
}
#checking1 {
margin-left:650px;
}
#checking2 {
margin-left:650px;
}
#checking3 {
margin-left:650px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<br/>
<div id ="checking">Current Position</div>
<div id ="checking1">Nothings Moving Bro</div>
<br/>
<div id ="checking3">Color State</div>
<div id ="checking2">Nope, still nothing</div>
<script>
// JavaScript code goes here
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth)/2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler,false);
document.addEventListener("keyup",keyUpHandler,false);
function keyDownHandler(e){
if(e.keycode == 39){
RightKeyPressed = true;
}else if(e.keycode == 37){
LeftKeyPressed = true;
}
}
function keyUpHandler(e){
if(e.keycode == 39){
RightKeyPressed = false;
}else if(e.keycode == 37){
LeftKeyPressed = false;
}
function randomInt(min,max){
return Math.floor(Math.random() * (max - min))+ min; }
function paddle(){
ctx.beginPath;
ctx.rect(paddleX,canvas.height - paddleheight,paddlewidth,paddleheight);
ctx.fillStyle="#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(x,y,ballRadius,0,Math.PI*2,false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function Draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawball();
paddle();
if(y + dy > canvas.height - 20 || y + dy < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if ( x + dx > canvas.width - 20 || x + dx < ballRadius){
var cx = randomInt(0,255);
var cy = randomInt(0,255);
var cz = randomInt(0,255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx; }
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y ;
checking2.innerHTML = color ;
}
}
if(RightKeyPressed && paddleX < canvas.width - 50 ){
paddleX += 7;
}else if(LeftKeyPressed && paddleX > 0){
paddleX -= 7;
}
setInterval(Draw,10);
</script>
</body>
</html>
Your code throws the error because it cannot find the function Draw():
setInterval(Draw, 10);
This is because your function is not in the same scope. Your code structure is like this:
function keyUpHandler(e) {
...
function Draw(){
//Codes here
}
...
}
...
setInterval(Draw, 10);
Since the Draw() function is inside the keyUpHandler(e), it cannot be seen from any outside function (that is functions that are on a higher level/scope).
Hope this clears your mind :)
Check out this fiddle , you closing bracket of function keyDownHandlercode is wrong
var checking1 = document.getElementById("checking1");
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var ballRadius = 20;
var dx = 2;
var dy = -2;
var paddleheight = 10;
var paddlewidth = 50;
var paddleX = (canvas.height - paddlewidth) / 2;
var RightKeyPressed = false;
var LeftKeyPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = true;
} else if (e.keycode == 37) {
LeftKeyPressed = true;
}
}
function keyUpHandler(e) {
if (e.keycode == 39) {
RightKeyPressed = false;
} else if (e.keycode == 37) {
LeftKeyPressed = false;
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function paddle() {
ctx.beginPath;
ctx.rect(paddleX, canvas.height - paddleheight, paddlewidth, paddleheight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath;
}
function drawball() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2, false);
ctx.fillStyle = "rgb(0,149,221)";
ctx.fill();
ctx.closePath();
}
function zan(){
alert('test');
}
function Draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawball();
paddle();
if (y + dy > canvas.height - 20 || y + dy < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dy = -dy;
}
if (x + dx > canvas.width - 20 || x + dx < ballRadius) {
var cx = randomInt(0, 255);
var cy = randomInt(0, 255);
var cz = randomInt(0, 255);
ctx.fillStyle = "rgb(cx,cy,cz)";
ctx.fill();
dx = -dx;
}
x += dx;
y += dy
var color = ctx.fillStyle;
checking1.innerHTML = " x: " + x + "y: " + y;
checking2.innerHTML = color;
}
if (RightKeyPressed && paddleX < canvas.width - 50) {
paddleX += 7;
} else if (LeftKeyPressed && paddleX > 0) {
paddleX -= 7;
}
setInterval(Draw, 10);
You probably forgot to close your keyuphandler function (currently you have like 3 function inside it until you finally close it at line 193).
add a function closure at about line 88 to close your keyuphandler.
Than you have a extra function closure at line 193 remove that and it works
(by function closure i mean brackets {} )

Categories

Resources