I am trying to use Javascript to reset my canvas to its original state. But the action does nothing when Ok is pressed. It gives me a dialog box when it is pressed, but it does not reset the canvas to its original state.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var GAME_SPEED = 1000 / 60; //game rate
var x = 100;
var y = 100;
var sideLength = 10;
var leftKey = false;
var rightKey = false;
var upKey = false;
var downKey = false;
var spaceKey = false;
var aKey = false;
var sKey = false;
var wKey = false;
var dKey = false;
var enterKey = false;
var bX = 100;
var bY = 100;
var sideLengthZ = 10;
var ctx;
window.onload = function() {
c = document.getElementById("myCanvas");
c.width = window.innerWidth * 0.9;
c.height = window.innerHeight * 0.9;
ctx = c.getContext('2d');
window.setInterval(function() {
draw();
draw2();
}, GAME_SPEED);
}
document.onkeyup = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = false;
break;
case 39:
rightKey = false;
break;
case 38:
upKey = false;
break;
case 40:
downKey = false;
break;
case 32:
spaceKey = false;
break;
case 65:
aKey = false;
break;
case 83:
sKey = false;
break;
case 68:
dKey = false;
break;
case 87:
wKey = false;
break;
case 13:
enterKey = false;
break;
}
}
document.onkeydown = function(event) {
event.preventDefault();
switch (event.keyCode) {
case 37:
leftKey = true;
break;
case 39:
rightKey = true;
break;
case 38:
upKey = true;
break;
case 40:
downKey = true;
break;
case 32:
spaceKey = true;
break;
case 65:
aKey = true;
break;
case 83:
sKey = true;
break;
case 68:
dKey = true;
break;
case 87:
wKey = true;
break;
case 13:
enterKey = true;
break;
}
}
function draw() {
if (leftKey == true) {
x--;
}
if (rightKey == true) {
x++;
}
if (upKey == true) {
y--;
}
if (downKey == true) {
y++;
}
if (spaceKey == true) {
sideLength++;
}
ctx.fillStyle = "#000000";
ctx.fillRect(x, y, sideLength, sideLength);
}
function draw2() {
if (aKey == true) {
bX--;
}
if (dKey == true) {
bX++;
}
if (wKey == true) {
bY--;
}
if (sKey == true) {
bY++;
}
if (enterKey == true) {
sideLengthZ++;
}
var b = document.getElementById("myCanvas");
var cntxt2 = ctx;
ctx.fillStyle = "#F00000";
ctx.fillRect(bX, bY, sideLengthZ, sideLengthZ);
}
function itReset()
{
var erase = confirm("Are you sure you want to delete?");
if (erase == true)
context.clearRect();
else
return false;
}
var ctx = document.querySelector("myCanvas").getContext("2d"),
angle = Math.random() * 360, // start angle (for HSL)
angleDlt = 60, // 60° ahead
step = 1; // "speed" for change
function createGradient() {
var gr = ctx.createLinearGradient(0, 0, 500, 0); // create gradient
gr.addColorStop(0, "hsl(" + (angle % 360) + ",100%, 50%)"); // start color
gr.addColorStop(0.5, "hsl(" + ((angle + (angleDlt/2)) % 360) + ",100%, 50%)");
gr.addColorStop(1, "hsl(" + ((angle + angleDlt) % 360) + ",100%, 50%)");
ctx.fillStyle = gr; // set as fill style
ctx.fillRect(0, 0, 500, 500); // fill area
}
</script>
</head>
<body>
<!--Marlon Jacques -->
<canvas id="myCanvas" style="border: 5px solid">
Your browser does not support the canvas element.
</canvas>
<button onclick="itReset()">Reset</button>
</body>
</html>
Use context.clearRect to clear the canvas.
Note that you need to get the context for your canvas because the context has the drawing (and clearing) methods--the canvas element itself does not have those methods.
function itReset(){
var erase = confirm("Are you sure you want to delete?");
if (erase == true){
ctx.clearRect(0,0,c.width,c.height);
}else{
return false;
}
Related
i'm a rookie and i try to learn by myself from different sources html css and now i'm on the block of JS
I'm actually doing a snake game but i have differents issues , the body of my snake supposed to be 3 blocks width , and he is also supposed to move with the arrow key !!
I'm kind stuck and request your knowledge to let me find the light again :)
//* I'm french and hope my english is correct *//
window.onload = function()
{
var canvasWidth = 900;
var canvasHeight = 600;
var blockSize = 30;
var ctx;
var delay = 100;
var snakee;
init();
function init()
{
var canvas = document.createElement('canvas')
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.border = "1px solid"
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
snakee = new Snake([[6,4],[5,4],[4,4],[3,4],[2,4]], "right");
refreshCanvas();
}
function refreshCanvas()
{
ctx.clearRect (0,0,canvasWidth, canvasHeight);
snakee.draw();
snakee.advance();
setTimeout(refreshCanvas, delay);
}
function drawBlock(ctx, position)
{
var x = position[0] * blockSize;
var y = position[1] * blockSize;
ctx.fillRect(x ,y , blockSize , blockSize );
}
function Snake(body, _direction)
{
this.body = body;
this.direction = "right";
this.draw = function ()
{
ctx.save();
ctx.fillStyle = "#ff0000";
for(var i = 0; i < this.body.lenght; i++);
{
drawBlock(ctx, this.body[i]);
}
ctx.restore();
};
this.advance = function()
{
var nextPosition = this.body[0].slice();
switch(this.direction)
{
case "left":
nexPosition[0] -= 1;
break;
case "right":
nextPosition[0] += 1;
break;
case "down":
nextPosition[1] -= 1;
break;
case "up":
nextPosition[1] += 1;
break;
default:
throw("Invalid Direction");
}
this.body.unshift(nextPosition);
this.body.pop();
};
this.setDirection = function(newDirection)
{
var allowedDirections;
switch(this.direction)
{
case "left":
case "right":
allowedDirections = ["up", "donw"];
break;
case "down":
case "up":
allowedDirections = ["left","right"]
break;
default:
throw("Invalid Direction");
}
if(allowedDirections.indexOf(newDirection) > -1 )
{
this.direction = newDirection;
}
};
}
}
document.addEventListener = function handleKeyDown(e)
{
const key = e.keyCode;
var newDirection;
switch(key)
{
case 37:
newDirection = "left";
break;
case 38:
newDirection = "right";
break;
case 39:
newDirection = "up";
break;
case 40:
newDirection = "down";
break;
default:
return;
}
snakee.setDirection(newDirection);
}
addEventListener is a function and takes at least two arguments
it should be:
document.addEventListener('keydown', (e) => {
let code = e.keyCode;
})
Where the first arg is the type of event to handle and the second is the callback - handling the event.
I've noticed a few bugs in your code:
for(var i = 0; i < this.body.*lenght*; i++); << remove semicolon, lenght is typo
case "down":
nextPosition[1] -= 1; << should incrementing
break;
case "up":
nextPosition[1] += 1; << should decrementing
break;
Also the addEventListener code should be inside the window.onload statement
or else it will not see the snakee object.
This code simply won't work for a full blown snake program, because
each block of the snake can have a separate direction, but it's a start.
so I have a 2d platformer in the works, and I'd like to add walls and platforms to it, but when I try to make a platform, it doesn't stop the player in front of it if they just walk forward, and instead it makes it sort of like a step/stairs.
Here's what I have so far:
var ctx, controller, rectangle, loop;
ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 200;
ctx.canvas.width = 400;
// Position of Player
rectangle = {
height: 25,
jumping: true,
width: 25,
x: 10,
x_velocity: 0,
y: 0,
y_velocity: 0
};
controller = {
left: false,
right: false,
up: false,
keyListener: function(event) {
var key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // Left
controller.left = key_state;
break;
case 39: // Right
controller.right = key_state;
break;
case 38: // Up
controller.up = key_state;
break;
};
}
};
loop = function() {
if (controller.up && rectangle.jumping == false) {
rectangle.y_velocity -= 25;
rectangle.jumping = true;
};
if (controller.left) {
rectangle.x_velocity -= 0.75;
};
if (controller.right) {
rectangle.x_velocity += 0.75;
};
// Gravity
rectangle.y_velocity += 1.5;
rectangle.x += rectangle.x_velocity;
rectangle.y += rectangle.y_velocity;
// Friction
rectangle.x_velocity *= 0.75;
rectangle.y_velocity *= 0.75;
// Floor
if (rectangle.y > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 150 - 25;
rectangle.y_velocity = 0;
};
// Platform
if (rectangle.y > 145 - 25 && rectangle.x > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 145 - 25;
rectangle.y_velocity = 0;
};
// Background
var bg = new Image;
bg.src = "https://i.imgur.com/He3uld9.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
// Player
var ply = new Image;
ply.src = "https://i.imgur.com/G4UUkIl.png";
ply.onload = function() {
ctx.drawImage(ply, rectangle.x, rectangle.y);
};
// Floor
var fl = new Image;
fl.src = "https://i.imgur.com/OoKP4Mm.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 150);
};
window.requestAnimationFrame(loop);
};
window.addEventListener("keydown", controller.keyListener);
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
<canvas style="border: 1px solid black;"></canvas>
The commented part that says Platform under the JS section is where my code for the platform currently is. As of now, it doesn't have an image or object for you to see it, but if you play the game, it is an invisible platform right above the floor.
What if you try to maintain a blockedRight and a blockedLeft property on the rectangle according to the zone you're in ? For instance, I have implemented a blockedRight boolean in the below where for Platform region, I turn it to true and for a Valid Region , I turn it back to false. Also I add this condition check in controller.right check as well.
So for an obstacle region that comes , you can make a condition that if the person is blockedRight and it tries to jump, you will set the blockedRight again to false. I am assuming the obstacles will be always taken care by jumping unless you have those which are greater than your jump height where more checks come in place.
var ctx, controller, rectangle, loop;
ctx = document.querySelector("canvas").getContext("2d");
// Screen size
ctx.canvas.height = 200;
ctx.canvas.width = 400;
// Position of Player
rectangle = {
height: 25,
jumping: true,
width: 25,
x: 10,
x_velocity: 0,
y: 0,
y_velocity: 0,
blockedRight:false
};
controller = {
left: false,
right: false,
up: false,
keyListener: function(event) {
var key_state = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 37: // Left
controller.left = key_state;
break;
case 39: // Right
controller.right = key_state;
break;
case 38: // Up
controller.up = key_state;
break;
};
}
};
loop = function() {
if (controller.up && rectangle.jumping == false) {
rectangle.y_velocity -= 25;
rectangle.jumping = true;
};
if (controller.left) {
rectangle.x_velocity -= 0.75;
};
if (controller.right && !rectangle.blockedRight) {
rectangle.x_velocity += 0.75;
};
// Gravity
rectangle.y_velocity += 1.5;
rectangle.x += rectangle.x_velocity;
rectangle.y += rectangle.y_velocity;
// Friction
rectangle.x_velocity *= 0.75;
rectangle.y_velocity *= 0.75;
// Floor
if (rectangle.y > 150 - 25) {
rectangle.jumping = false;
rectangle.y = 150 - 25;
rectangle.y_velocity = 0;
};
// Valid ground
if(rectangle.x <= 150 - 25){
rectangle.blockedRight = false;
}
// Platform
if (rectangle.y > 145 - 25 && rectangle.x > 150 - 25) {
rectangle.blockedRight = true;
rectangle.jumping = false;
rectangle.y = 145-25;
rectangle.y_velocity = 0;
};
// Background
var bg = new Image;
bg.src = "https://i.imgur.com/He3uld9.png";
bg.onload = function() {
ctx.drawImage(bg, 0, 0);
};
// Player
var ply = new Image;
ply.src = "https://i.imgur.com/G4UUkIl.png";
ply.onload = function() {
ctx.drawImage(ply, rectangle.x, rectangle.y);
};
// Floor
var fl = new Image;
fl.src = "https://i.imgur.com/OoKP4Mm.png";
fl.onload = function() {
ctx.drawImage(fl, 0, 150);
};
window.requestAnimationFrame(loop);
};
window.addEventListener("keydown", controller.keyListener);
window.addEventListener("keyup", controller.keyListener);
window.requestAnimationFrame(loop);
<canvas style="border: 1px solid black;"></canvas>
Hello I want to know how can I make the canvas shape circle in the below code.
The code is about moving a object with keyboard keys. I tried to make the circle out of this box but it just disappeared and i am not really sharp. Can some help me make this canvas circle without affecting code.
sorry but i have to write something more because SO says body has all code... i don't know what to say now (make the canvas circle)(make the canvas circle)(make the canvas circle)
<!DOCTYPE html>
<html>
<head></head>
<body>
<canvas id="myCanvas" width='800' height='800' border-radius= ></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
let circle = new Path2D(); // <<< Declaration
circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'lightblue';
context.fill(circle); // <<< pass circle to context
context.lineWidth = 10;
context.strokeStyle = '#000066';
context.stroke(circle);
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}
function onKeyUp(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}
//neccessary variables
var tickX = 10;
var tickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function drawStuff() {
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.clearRect(0, 0, 800, 800);
c.fillStyle = "lightblue";
c.fillRect(tickX, tickY, 100, 100);
if (keyD == true) {
tickX += 1;
}
if (keyS == true) {
tickY += 1;
}
if (keyA == true) {
tickX--;
}
if (keyW == true) {
tickY--;
}
}
window.requestAnimationFrame(drawStuff);
</script>
I moved the circle code into the drawstuff function as that is where it has to run, and removed the use of fillRect.
You can see the result here:
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
//event listener
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);
function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}
function onKeyUp(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}
//neccessary variables
var tickX = 10;
var tickY = 10;
var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;
//main animation function
function drawStuff() {
window.requestAnimationFrame(drawStuff);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
c.clearRect(0, 0, 200, 200);
let circle = new Path2D(); // <<< Declaration
circle.arc(100 + tickX, 100 + tickY, 70, 0, 2 * Math.PI, false);
c.fillStyle = 'purple';
c.fill(circle); // <<< pass circle to context
c.lineWidth = 10;
c.strokeStyle = '#000066';
c.stroke(circle);
if (keyD == true) {
tickX += 1;
}
if (keyS == true) {
tickY += 1;
}
if (keyA == true) {
tickX--;
}
if (keyW == true) {
tickY--;
}
}
window.requestAnimationFrame(drawStuff);
Focus this area, then use keys <b>d, s, a, w</b><br />
<canvas id="myCanvas" width='200' height='200' style="border: 1px solid #f4f4f4" ></canvas>
I am making a javascript game, and the animated sprite blinks when he moves i think it has to do with the speed of the animation because I also need to slow it down. here is my code for updateign the animation
var playerani = setInterval(function(){
if(animate == true){
if(aniframe == maxframes){
aniframe = 1
}else{
aniframe += 1;
}
}
if(controller.left == true){
animate = true;
window.aniimgY = 576;
}else if(controller.up == true){
animate = true;
window.aniimgY = 512;
}else if(controller.down == true){
animate = true;
window.aniimgY = 640;
}else if(controller.right == true){
animate = true;
window.aniimgY = 704;
}else{
animate = false;
aniframe = 0;
}
},10)
Here is The spritesheet
, And a Gif of the animation
You can test the game here
As #HanYolo suggested, set var maxframes = 8; :
var aniframe = 0;
var maxframes = 8;
var animate = false;
window.aniimg = document.getElementById("aniimg1")
var timer = null;
var aniTimer = null;
var levelnum = 0;
var img = document.getElementById("img")
var img2 = document.getElementById("img2")
var c = document.getElementById("c");
var ctx = c.getContext('2d')
var props = document.getElementById("props");
var prps = c.getContext('2d')
var tilesize = 32;
var tiles = 10;
player = {
size: 10,
x: 150,
y: 150,
v: 2,
}
controller = {
up: false,
right: false,
left: false,
down: false,
keyParse: function(key) {
switch (key) {
//keydowns
case 38:
this.up = true;
break;
case 37:
this.left = true;
break;
case 39:
this.right = true;
break;
case 40:
this.down = true;
break;
}
},
keyStop: function(key) {
switch (key) {
//keydowns
case 38:
this.up = false;
break;
case 37:
this.left = false;
break;
case 39:
this.right = false;
break;
case 40:
this.down = false;
break;
}
}
}
function drawlvl() {
for (y = 0; y < lvl[levelnum].length; y++) {
for (x = 0; x < lvl[levelnum][y].length; x++) {
switch (lvl[levelnum][y][x]) {
case 0:
//nw grass
var imgvar = img
var sx = 32;
var sy = 192;
break;
case 1:
//w dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 2:
//nw top dirt
var imgvar = img
var sx = 128;
var sy = 96;
break;
case 3:
//nw bottom dirt
var imgvar = img2
var sx = 95;
var sy = 320;
break;
case 4:
//lvl up dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 5:
//lvl down dirt
var imgvar = img
var sx = 224;
var sy = 160;
break;
case 6:
//w water
var imgvar = img
var sx = 0;
var sy = 416;
break;
case 7:
//w water side left
var imgvar = img
var sx = 0;
var sy = 288;
break;
case 8:
//w water side right
var imgvar = img2
var sx = 223;
var sy = 128;
break;
}
ctx.drawImage(imgvar, sx, sy, 32, 32, x * tilesize, y * tilesize, tilesize, tilesize)
}
}
}
walkable_blocks = [1, 6, 7, 8]
walkable_props = [0, 8, 9, 10, 11, 12]
lvlup_blocks = [4]
lvldown_blocks = [5]
function gameLoop() {
if (controller.up == true) {
player.newY = player.y - player.v
} else if (controller.left == true) {
player.newX = player.x - player.v
} else if (controller.right == true) {
player.newX = player.x + player.v
} else if (controller.down == true) {
player.newY = player.y + player.v
} else {
player.newY = player.y;
player.newX = player.x;
}
function playerani() {
if (animate == true) {
if (aniframe == maxframes) {
aniframe = 1
} else {
aniframe += 1;
}
}
if (window.aniimgY == null) {
window.aniimgY = 640;
}
if (controller.left == true) {
animate = true;
window.aniimgY = 576;
} else if (controller.up == true) {
animate = true;
window.aniimgY = 512;
} else if (controller.down == true) {
animate = true;
window.aniimgY = 640;
} else if (controller.right == true) {
animate = true;
window.aniimgY = 704;
} else {
animate = false;
aniframe = 0;
}
}
player.col = Math.floor((player.newX + 5) / tilesize)
player.row = Math.floor((player.newY + 5) / tilesize)
tileval = lvl[levelnum][player.row][player.col]
propval = propsArr[levelnum][player.row][player.col]
ctx.fillStyle = "black"
if (walkable_blocks.includes(tileval) && walkable_props.includes(propval)) {
player.y = player.newY;
player.x = player.newX;
if (player.x <= 0) {
player.x = 0
}
if (player.y <= 0) {
player.y = 0
}
if (player.x + player.size >= c.width) {
player.x = c.width - player.size;
}
if (player.y + player.size >= c.height) {
player.y = c.height - player.size;
}
} else if (lvlup_blocks.includes(tileval)) {
document.getElementById("body").style.ainmation = "fadeInAnimation";
document.getElementById('body').style.animationPlayState = "running";
if (timer == null) {
timer = setTimeout(function() {
levelnum++;
player.x = 280;
player.y = 150;
timer = null;
}, 2500)
if (aniTimer == null) {
aniTimer = setTimeout(function() {
document.getElementById("body").style.animationPlayState = "paused";
clearTimeout(aniTimer)
aniTimer = null;
}, 5000)
}
} else {
}
} else if (lvldown_blocks.includes(tileval)) {
document.getElementById("body").style.ainmation = "fadeInAnimation";
document.getElementById('body').style.animationPlayState = "running";
if (timer == null) {
timer = setTimeout(function() {
levelnum--;
player.x = 33;
player.y = 150;
timer = null;
}, 2500)
}
if (aniTimer == null) {
aniTimer = setTimeout(function() {
document.getElementById("body").style.animationPlayState = "paused";
clearTimeout(aniTimer);
aniTimer = null;
}, 5000)
}
} else {
player.y = player.y;
player.x = player.x;
if (player.x <= 0) {
player.x = 0
}
if (player.y <= 0) {
player.y = 0
}
if (player.x + player.size >= c.width) {
player.x = c.width - player.size;
}
if (player.y + player.size >= c.height) {
player.y = c.height - player.size;
}
}
ctx.fillRect(0, 0, c.width, c.height)
drawlvl()
drawprops()
drawEnemy()
playerani()
ctx.drawImage(window.aniimg, 64 * (Math.floor(aniframe)), window.aniimgY, 64, 64, player.x - 16, player.y - 16, 48, 48)
}
var gameintertval = setInterval(function() {
gameLoop()
}, 10)
document.addEventListener('keydown', function(event) {
controller.keyParse(event.keyCode)
})
document.addEventListener('keyup', function(event) {
controller.keyStop(event.keyCode)
})
body {
zoom: 100%;
animation: fadeInAnimation ease 5s;
animation-play-state: paused;
animation-iteration-count: infinite;
}
#keyframes fadeInAnimation {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
canvas{
position: absolute;
}
#props{
z-index: 1000;
}
#c{
z-index: -1000;
}
<html>
<head>
<title>TileGame</title>
<base href="http://ryangrube.com/projects/tilegame/">
</head>
<body id="body">
<img id="img" style="display: none;" src="TileSet_V1.png">
<img id="img2" style="display: none;" src="TileSet_V2.png">
<img id="img3" style="display: none;" src="TileSet_V3.png">
<img id="aniimg1" style="display: none;" src="no_dagger.png">
<img id="aniimg2" style="display: none;" src="dagger.png">
<canvas id="c" width="320" height="320" style="background-color: black;border:3px solid black;"></canvas>
<canvas id="props" width="320" height="320" style="border:3px solid black;"></canvas>
<script src="map.js"></script>
<script src="props.js"></script>
<script src="drawprops.js"></script>
<script src="enemy.js"></script>
<script src="drawenemy.js"></script>
</body>
</html>
I have been trying to make my first game in javascript, its a pong like game where two players move their rectangles around to bump the ball in the other direction. I want it so that when player one hits the "a" key, their character moves left, when they hit the d key they move right.
Right now, nothing happens when I click the desired keys.
This is my current code:
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 65:
p1dx = 1;
case 68:
p1dx = -1;
case 37:
p2dx = -1;
case 39:
p2dx = 1;
default:
break;
}
});
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
You're adding another keypress handler every 10 ms. So after a few seconds there are thousands of handlers running every time you press a key, and this is probably bogging down the browser. You should just bind the handler once, outside the draw function.
And in the function, you need break statements in each case.
Your code tests are also wrong. Lowercase a is 97, not 65. And the values of p1dx are backwards -- if you want to go left, it should be -1, not 1.
$(document).ready(function() {
// things needed
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//positions of elements at start
var ballposx = 400;
var ballposy = 50;
var balldx = 1;
var balldy = 2;
var balld2x = 0;
var balld2y = 0;
var p1posx = 80;
var p1posy = 225;
var p1dx = 0;
var p1dy = 0;
var p2posx = 620;
var p2posy = 225;
var p2dx = 0;
var p2dy = 0;
$(window).keypress(function(e) {
var code = e.which;
switch (code) {
case 97:
p1dx = -1;
break;
case 100:
p1dx = 1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
//goal1
ctx.fillStyle = "#0F3F0F";
var goal1 = ctx.fillRect(0, 150, 50, 150);
//goal2
ctx.fillStyle = "#204050";
var goal2 = ctx.fillRect(750, 150, 50, 150);
ctx.beginPath();
//ball
var ball = ctx.arc(ballposx, ballposy, 60, 0, 2 * Math.PI);
ctx.stroke();
//p1
ctx.fillStyle = "#FF0000";
var p1 = ctx.fillRect(p1posx, p1posy, 40, 75);
//p2
ctx.fillStyle = "#0000FF";
var p1 = ctx.fillRect(p2posx, p2posy, 40, 75);
p1posx += p1dx;
p2posx += p2dx;
balldx += balld2x;
balldy += balld2y;
ballposx += balldx;
ballposy += balldy;
if (ballposy === 240) {
balldy = -1;
} else if (ballposy === 60) {
balldy = 1;
} else if (ballposx === 60) {
balldx = 1;
} else if (ballposx === 740) {
balldx = -1;
} else if (ballposx === p1posx && ballposy < p1posy) {
balldx = 1;
} else if (ballposx === p2posx && ballposy < p2posy) {
balldx = -1;
}
}
setInterval(draw, 10);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<canvas id="myCanvas" width="800px" height="300px" style="border:1px solid #000000;"> Sorry your browser doesnt support this!</canvas></center>
I didn't check the whole code, but ou should add the break; statement in every case, not just the default.
For example, your code should be something like:
$(window).keypress(function(e){
var code = e.which;
switch (code)
{
case 65:
p1dx = 1;
break;
case 68:
p1dx = -1;
break;
case 37:
p2dx = -1;
break;
case 39:
p2dx = 1;
break;
default:
break;
}
});