How to make JavaScript canvases overlap other canvases - javascript

var canvas = document.getElementById('PongPad1');
// var canvasSize = document.getElementById("PongPad1").style.height;
var PongPad1 = canvas.getContext('2d');
PongPad1.speed = 3;
PongPad1.w = 50;
PongPad1.h = 100;
PongPad1.x = "";
PongPad1.y = "";
if(PongPad1.x == ""){
PongPad1.x = 20;
}
if(PongPad1.y == ""){
PongPad1.y = 20;
}
function draw() {
PongPad1.fillStyle = 'black';
PongPad1.fillRect( PongPad1.x , PongPad1.y , PongPad1.w, PongPad1.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 38) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h)
if(PongPad1.y > 0){
PongPad1.y = PongPad1.y - PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 40) {
PongPad1.clearRect(PongPad1.x, PongPad1.y, PongPad1.w, PongPad1.h);
//Canvas hieght - PongPad1.h
if(PongPad1.y < 175){
PongPad1.y = PongPad1.y + PongPad1.speed;
}
draw();
//console.log(PongPad1.y);
}
});
var canvas1 = document.getElementById('PongPad2');
// canvas.setAttribute('style', 'border: 1px solid; position: fixed; top: 8px; left: 8px; z-index: 0; width: 500px; height: 500px;');
var PongPad2 = canvas1.getContext('2d');
PongPad2.speed = 3;
PongPad2.w = 50;
PongPad2.h = 100;
PongPad2.x = "";
PongPad2.y = "";
if(PongPad2.x == ""){
PongPad2.x = window.innerWidth - (40 + PongPad2.w);
}
if(PongPad2.y == ""){
PongPad2.y = 20;
}
function draw2() {
PongPad2.fillStyle = 'black';
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
document.addEventListener('keydown', function(event) {
if(event.keyCode == 87) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h)
if(PongPad2.y > 0){
PongPad2.y = PongPad2.y - PongPad2.speed;
}
draw2();
PongPad2.fillRect( PongPad2.x , PongPad2.y , PongPad2.w, PongPad2.h);
}
});
document.addEventListener('keydown', function(event) {
if(event.keyCode == 83) {
PongPad2.clearRect(PongPad2.x, PongPad2.y, PongPad2.w, PongPad2.h);
//Canvas hieght - PongPad1.h
if(PongPad2.y < 175){
PongPad2.y = PongPad2.y + PongPad2.speed;
}
draw2();
}
});
var canvas2 = document.getElementById('ball');
var ball = canvas2.getContext('2d');
ball.speed = 1;
ball.w = 10;
ball.h = 10;
ball.dx = "";
ball.dy = "";
if(ball.dx == ""){
ball.dx = 1 * (Math.round(Math.random()) * 2 - 1);
}
if(ball.dy == ""){
ball.dy = 1 * (Math.round(Math.random()) * 2 - 1);
}
ball.x = "";
ball.y = "";
if(ball.x == ""){
ball.x = 960;
}
if(ball.y == ""){
ball.y = -300;
}
function draw3() {
ball.fillStyle = 'black';
ball.fillRect( ball.x , ball.y , ball.w, ball.h);
}
setInterval(() => {
ball.clearRect( ball.x , ball.y , ball.w, ball.h);
ball.x = ball.x + (ball.speed * ball.dx);
ball.y = ball.y + (ball.speed * ball.dy);
draw3();
if(ball.y < 0){
ball.dy = 1;
}
//Math.round(window.innerHeight/2)
if(ball.y > 200){
ball.dy = -1;
}
draw3();
if(ball.x > window.innerWidth){
ball.dx = -1;
ball.speed = 1;
}
if(ball.x < 0){
ball.dx = 1;
ball.speed = 1;
}
if(PongPad1.x < ball.x + ball.w &&
PongPad1.x + PongPad1.w > ball.x &&
PongPad1.y < ball.y + ball.h &&
PongPad1.y + PongPad1.h > ball.y)
{
ball.dx = 1;
//ball.speed++;
}
if(PongPad2.x < ball.x + ball.w &&
PongPad2.x + PongPad2.w > ball.x &&
PongPad2.y < ball.y + ball.h &&
PongPad2.y + PongPad2.h > ball.y)
{
ball.dx = -1;
//ball.speed++;
}
//console.log(ball.y);
}, 10);
var test = window.innerWidth ;
var test2 = window.innerHeight ;
document.getElementById("test").textContent = "" + test + "," + test2 + "";
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="Pangea 8 logo 3.png" type="image/x-icon">
<meta name="keywords" content="Pangea 8"/>
</head>
<style>
.work{
position: static;
border: 3px solid #73AD21;
}
</style>
<body id="body">
<p id ="test">
hello
</p>
<div >
<canvas class = "work" id="ball" height = "469px" width = "1900px" ></canvas>
<canvas class = "work" id="PongPad1" height = "275px" > </canvas>
<canvas class = "work" id="PongPad2" height = "275px" width = "1900px" ></canvas>
</div>
</body></html>
^ Is my Pong game. Use W,S and Up, Down to make the paddles appear. I made the canvases have a green border so you can see them better. I want these canvases to be on the same plane, instead of the 3. They are not in synch, I need them to be. How can I make them overlap so they are on the same level?

position:absolute;
top:0;
left:0;
this created my desired outcome.

Related

How to make my keyup function work inside of my game

This is somewhat a long shot, but I have been recently working on a game, and I have been pretty proud of it. Although it is no Minecraft, for my level of expertise, it is looking pretty good. There is just one problem with it though. My character travels all over the place. I have never been able to get him to only move one block. If there is anyone out there with a high level of coding expertise, please look at this code. There is a lot of code, so it might take a while, but I appreciate all the help I can get. If you can spot the problem, please notify me. Thank you.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
setInterval(terrainJumpLoop, 100);
setInterval(playerLeftLoop, 100);
setInterval(playerRightLoop, 100);
canvas.width = 1500;
canvas.height = 500;
var highTerrain = [];
var middleTerrain = [];
var lowTerrain = [];
var oreTerrain = [];
var biome = "";
var biomeSelector = 0;
var playerBlock = 0;
var terrainLength = canvas.width/25;
var unevenTerrainLocator = 0;
var gravityVar = 0;
var gravityStrength = 0;
var touchingGround = false;
var canMove = true;
var gameOn = false;
window.onerror = function (msg, url, lineNo, columnNo, error) {
document.getElementById("paragraph").innerHTML = "Game has Stopped Abruptly Due to Error in Code";
document.getElementById("wrongCodeLine").innerHTML = msg;
document.getElementById("errorLineNo").innerHTML = "Line Number: " + lineNo.toString();
window.stop();
};
var Player = {
x:0,
y:0,
width:25,
height:25,
color:"gold"
};
function paintGameTrees(x, y){
alert(x);
alert(y);
}
function paintGameTerrain(){
var grassBlock = {
width:25,
height:25,
color:"green"
};
var dirtBlock = {
width:25,
height:25,
color:"brown"
};
var stoneBlock = {
width:25,
height:25,
color:"gray"
};
var coalBlock = {
width:25,
height:25,
color:"#383838"
};
var ironBlock = {
width:25,
height:25,
color:"#C0C0C0"
};
var lava = {
width:25,
height:25,
color:"red"
};
var snowBlock = {
width:25,
height:25,
color:"white"
};
for(i = 0; i < terrainLength; i++){
if(highTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 100, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(highTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 100, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(middleTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 75, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(middleTerrain[i] === 1){
paintGameItems(i*25, canvas.height - 75, dirtBlock.width, dirtBlock.height, dirtBlock.color);
}
else if(middleTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 75, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(lowTerrain[i] === 0){
paintGameItems(i*25, canvas.height - 50, grassBlock.width, grassBlock.height, grassBlock.color);
}
else if(lowTerrain[i] === 1){
paintGameItems(i*25, canvas.height - 50, dirtBlock.width, dirtBlock.height, dirtBlock.color);
}
else if(lowTerrain[i] === 2){
paintGameItems(i*25, canvas.height - 50, stoneBlock.width, stoneBlock.height, stoneBlock.color);
}
else if(lowTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 50, snowBlock.width, snowBlock.height, snowBlock.color);
}
}
for(i = 0; i < terrainLength; i++){
if(oreTerrain[i] === 2){
paintGameItems(i*25, canvas.height - 25, stoneBlock.width, stoneBlock.height, stoneBlock.color);
}
else if(oreTerrain[i] === 4){
paintGameItems(i*25, canvas.height - 25, coalBlock.width, coalBlock.height, coalBlock.color);
}
else if(oreTerrain[i] === 5){
paintGameItems(i*25, canvas.height - 25, ironBlock.width, ironBlock.height, ironBlock.color);
}
else if(oreTerrain[i] === 6){
paintGameItems(i*25, canvas.height - 25, lava.width, lava.height, lava.color)
}
else if(oreTerrain[i] === 7){
paintGameItems(i*25, canvas.height - 25, lava.width, lava.height, lava.color)
}
}
}
function setItemAttributes(){
console.log("ItemAttributes Successfully Set");
paintGameItems(Player.x, Player.y, Player.width, Player.height, Player.color);
console.log("paintGameItems Successfully Called");
}
function randomTerrain(){
console.log("randomTerrain successfully called");
/*
If the number passed is 0, then the block will be grass
If the number 1 is passed, then the block will be dirt
If the number 2 is passed, then the block will be stone
If the number 3 is passed, then the block will be nothing
If the number 4 is passed, then the block will be coal
If the number 5 is passed, then the block will be iron
If the number 6 is passed, then the block will be lava
If the number 7 is passed, then the block will be snow
*/
var terrainVar = Math.random() * 10;
var oreVar = Math.random() * 10;
if(biome === "plains") {
if (terrainVar > 0 && terrainVar < 6) {
highTerrain.push(0);
middleTerrain.push(1);
lowTerrain.push(2)
} else if (terrainVar > 6 && terrainVar < 9) {
highTerrain.push(3);
middleTerrain.push(0);
lowTerrain.push(1);
} else {
highTerrain.push(3);
middleTerrain.push(3);
lowTerrain.push(0);
}
console.log("oreVar = " + oreVar);
if (oreVar < 6) {
oreTerrain.push(2);
} else if (oreVar > 6 && oreVar < 8) {
oreTerrain.push(4);
} else if (oreVar > 8 && oreVar < 9) {
oreTerrain.push(5);
} else if (oreVar > 9) {
oreTerrain.push(6)
}
}
else if(biome === "taiga") {
if (terrainVar > 0 && terrainVar < 6) {
highTerrain.push(7);
middleTerrain.push(7);
lowTerrain.push(2)
} else if (terrainVar > 6 && terrainVar < 9) {
highTerrain.push(3);
middleTerrain.push(7);
lowTerrain.push(7);
} else {
highTerrain.push(3);
middleTerrain.push(3);
lowTerrain.push(7);
}
console.log("oreVar = " + oreVar);
if (oreVar < 6) {
oreTerrain.push(2);
} else if (oreVar > 6 && oreVar < 8) {
oreTerrain.push(4);
} else if (oreVar > 8 && oreVar < 9) {
oreTerrain.push(5);
} else if (oreVar > 9) {
oreTerrain.push(6)
}
}
}
function paintGameItems(itemX, itemY, itemWidth, itemHeight, itemColor){
//console.log(itemX, itemY, itemWidth, itemHeight);
ctx.beginPath();
ctx.fillStyle = itemColor;
ctx.fillRect(itemX, itemY, itemWidth, itemHeight);
ctx.fill();
}
function selectBiome(){
biomeSelector = Math.random() * 10;
if(biomeSelector <= 7){
biome = "plains";
}
else if(biomeSelector > 7){
biome = "taiga";
}
}
function playerLocationTracker(){
console.log("Player.x = " + Player.x + ". canMove = " + canMove + ". playerBlock = " + playerBlock);
}
function playerJump(e){
addEventListener("keydown", function(e) {
if (e.keyCode === 32 || e.keyCode === 87 || e.keyCode === 38) {
if (touchingGround) {
for (i = 0; i < 1; i++) {
Player.y -= 1;
}
}
}
});
}
function playerLeft(e){
addEventListener("keydown", function(e) {
if(canMove) {
if (e.keyCode === 65 || e.keyCode === 37){
console.log("Left");
canMove = false;
playerBlock -= 0.04;
Player.x -= 0.4;
canMove = true;
e.keyCode = 0;
}
}
});
}
function playerRight(e){
addEventListener("keydown", function(e) {
if (canMove){
if (e.keyCode === 68 || e.keyCode === 39) {
console.log("Right");
canMove = false;
playerBlock += 0.04;
Player.x += 0.4;
canMove = true;
e.keyCode = 0;
}
}
});
}
function playerGravity(){
unevenTerrainLocator = Math.round(playerBlock);
if(highTerrain[unevenTerrainLocator] === 0 || highTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 12;
}
else if(middleTerrain[unevenTerrainLocator] === 0 || middleTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 100;
}
else if(lowTerrain[unevenTerrainLocator] === 0 || lowTerrain[unevenTerrainLocator] === 7){
gravityVar = canvas.height - 75
}
if(gravityVar <= Player.y){
Player.y = gravityVar;
gravityStrength = 0;
touchingGround = true;
}
else if(gravityVar > Player.y){
touchingGround = false;
gravityStrength +=5;
Player.y += gravityStrength;
}
}
function terrainJumpLoop(){
if(gameOn){
ctx.clearRect(0, 0, canvas.width, canvas.height);
playerGravity();
playerJump();
playerLocationTracker();
paintGameItems(Player.x, Player.y, Player.width, Player.height, Player.color);
paintGameTerrain();
}
}
function playerLeftLoop(){
playerLeft();
}
function playerRightLoop(){
playerRight();
}
function initializeGame(){
var treeX = (Math.round(Math.random()*(canvas.width/25)))*25;
var treeY = 0;
if(highTerrain[treeX/25] === 0){
treeY = canvas.height - 100;
}
else if(middleTerrain[treeX/25] === 0){
treeY = canvas.height - 75;
}
else if(lowTerrain[treeX/25]){
treeY = canvas.height - 50;
}
paintGameTrees(treeX, treeY);
if (biome === "plains") {
document.getElementById('mediaOverworld').play();
}
else if(biome === "taiga"){
document.getElementById('mediaGlaciers').play();
}
}
function startGameFunction() {
console.clear();
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('mediaOverworld').pause();
document.getElementById('mediaOverworld').currentTime = 0;
document.getElementById('mediaGlaciers').pause();
document.getElementById('mediaGlaciers').currentTime = 0;
highTerrain = [];
middleTerrain = [];
lowTerrain = [];
oreTerrain = [];
selectBiome();
Player.x = 0;
Player.y = 0;
document.getElementById("paragraph").innerHTML = "Music and Game Has Successfully Started";
console.log("Game Has Successfully Started");
setItemAttributes();
for(i = 0; i < terrainLength; i++){
randomTerrain();
console.log("Terrain Layer Successfully Generated")
}
console.log(highTerrain);
console.log(middleTerrain);
console.log(lowTerrain);
console.log(oreTerrain);
initializeGame();
paintGameTerrain();
document.getElementById("startBtn").innerHTML = "Reset the Game";
gameOn = true;
}
body{
background-color:black;
color:white;
}
canvas{
background-color:aqua;
margin:0 auto;
}
#ifError {
color: red;
font-family: "Arial Black";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple 2D JavaScript Platformer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<br>
<button onclick="startGameFunction()" id="startBtn">Start The Game</button>
<p id="paragraph"></p>
<div id="ifError">
<p id="wrongCodeLine"></p>
<p id="errorLineNo"></p>
</div>
<audio id="mediaOverworld">
<source src="Audio/Overworld.mp3">
</audio>
<audio id="mediaGlaciers">
<source src="Audio/Glaciers.mp3">
</audio>
<script src="game.js"></script>
</body>
</html>
This is a lot of code to debug, but if you can do it, I will thank you a lot.

How can i make the bullet not move with the character when looking either right or left?

I am having a problem where when I fire either left or right, once i move the character the bullets direction will change while its still fired. I am using the protagonist picture as the condition to either shoot right or left but i would like the bullet to keep firing in the fired direction even if i change the movement of the character
I am a beginner in Javascript and I'm using canvas to create a game for a college project.
if (moveBullet) {
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletX += 20;
}
if (s == "Protagenist_Left_Jet.png") {
bulletX -= 20;
}
if (bulletX >= canvas.width) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
if (bulletX <= 0) {
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height + 50;
}
}
Full Code
<!DOCTYPE html>
<body>
<div id="canvasesdiv" style="text-align: center;">
<canvas id="canvas1" width="800" height="500" tabIndex="0" style="background: url('Level 1.png');position: relative; display: block;">
</div>
<script>
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
//get the animation frame depending on the browser engine
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
//Hero Attributes
var jetPackAudio = new Audio();
jetPackAudio.src = "Jetpack Sound.mp3";
var heroPic = new Image();
var heroX ;
var heroY ;
//Decides where the hero is looking
var heroRight = false;
var life = 3;
var heroWidth = 50 ;
var heroHeight = 50 ;
var gravity = 5;
heroX = 20;
heroY = 440;
heroPic.src = "Protagenist_Stand_Jet.png";
function drawHero(x,y)
{
ctx.drawImage(heroPic,x,y,heroWidth,heroHeight);
}
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
// Key Attribute
var key = new Image();
key.src = "Key1.png"
var keyX ;
var keyY ;
var keyCounter = 0;
var keyWidth = 30 ;
var keyHeight = 30 ;
function drawKey()
{
ctx.drawImage(key,keyX,keyY,keyWidth,keyHeight);
}
var killCounter = 0 ;
var levelKillCounter;
// Monster 1 Attributes
var monster1 = new Image();
monster1.src = "Monster1_Left.png"
var m1MoveLeft = true;
var m1X ;
var m1Y ;
var m1Width = 50 ;
var m1Height = 50 ;
function drawMonster1()
{
ctx.drawImage(monster1,m1X,m1Y,m1Width,m1Height);
}
// Monster 2 Attributes
var monster2 = new Image();
monster2.src = "Monster 2_Right.png"
var m2MoveRight = true;
var m2X ;
var m2Y ;
var m2Width = 50 ;
var m2Height = 50 ;
function drawMonster2()
{
ctx.drawImage(monster2,m2X,m2Y,m2Width,m2Height);
}
// Monster 3 Attributes
var monster3 = new Image();
monster3.src = "Monster3_Right.png"
var m3MoveRight = true;
var m3X ;
var m3Y ;
var m3Width = 50 ;
var m3Height = 50 ;
function drawMonster3()
{
ctx.drawImage(monster3,m3X,m3Y,m3Width,m3Height);
}
// Hit Bottom
hitBottom = function() {
var rockbottom = canvas.height - heroHeight;
if (heroY > rockbottom) {
heroY = rockbottom;
}
}
//Bullet Attribute
var bulletX;
var bulletY;
const ammo = [];
var moveBullet = false;
var bulletImage = new Image();
bulletImage.src = 'Bullet.png';
function drawBullet(x,y)
{
ctx.drawImage(bulletImage,bulletX,bulletY);
}
//this function is used to detect a hit monster 1
function getDistanceHit1() {
var xRect = (m1X - bulletX);
var yRect = (m1Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 2
function getDistanceHit2() {
var xRect = (m2X - bulletX);
var yRect = (m2Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect a hit monster 3
function getDistanceHit3() {
var xRect = (m3X - bulletX);
var yRect = (m3Y - bulletY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//this function is used to detect if the player got the key
function getDistanceKey() {
var xRect = (keyX - heroX);
var yRect = (keyY - heroY);
return Math.sqrt(Math.pow((xRect), 2) + Math.pow((yRect), 2));
}
//configure the audio files
var fireAudio = new Audio();
fireAudio.src = "fire.mp3";
var hitAudio = new Audio();
hitAudio.src = "neck_snap.wav"
//Hero Movement
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
window.addEventListener("keydown", heroControl);
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
// 38 is up arrow, 87 is the W key
if (event.keyCode == 38 || event.keyCode == 87) { //Jump
upPressed = true;
console.log("HeroY = " + heroY);
}
// 39 is right arrow, 68 is thw D key
else if (event.keyCode == 39 || event.keyCode == 68) { //move Right
rightPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 37 || event.keyCode == 65) { // Move Left
leftPressed = true;
console.log("Herox = " + heroX);
}
else if(event.keyCode == 40 || event.keyCode == 83) { // Move Left
downPressed = true;
console.log("Heroy = " + heroY);
}
}
//Touch Controls
canvas.addEventListener("touchstart", handleTouchStart, false);
function handleTouchStart(touchEvent) { //event handler for touch events
var rect = canvas.getBoundingClientRect(); //to get canvas offsets
let touchX = touchEvent.changedTouches[0].clientX - rect.left;
let touchY = touchEvent.changedTouches[0].clientY - rect.top;
if (touchX <= canvas.width && touchX > canvas.width - 200) {
rightPressed = true;
}
if (touchX >= 0 && touchX < canvas.width - 600) {
leftPressed = true;
}
if (touchY >= 0 && touchY < canvas.height - 200) {
upPressed = true;
}
if (touchY <= canvas.height && touchY > canvas.height - 200) {
downPressed = true;
}
}
function moveHero() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(rightPressed) {
if(heroX < canvas.width - 53){
heroPic.src = "Protagenist_Right_Jet.png"
heroRight = true;
heroX = heroX + 10;
heroRight = true;
rightPressed = false;
}
else
{
rightPressed = false;
heroRight = false;
}
}
if(leftPressed) {
if(heroX > 0){
heroX = heroX - 10;
heroLeft = true;
heroPic.src = "Protagenist_Left_Jet.png";
bulletImage.src = "left_bullet.png";
leftPressed = false;
}
else
{
leftPressed = false;
heroLeft = false;
}
}
if(upPressed) {
if(heroY > 0){
heroY = heroY - 20;
heroStand = true;;
jetPackAudio.play();
heroPic.src = "Protagenist_Stand_Jet.png";
upPressed = false;
}
else
{
upPressed = false;
heroStand = false;;
}
}
if(downPressed) {
if(heroY < canvas.height){
heroPic.src = "Protagenist_Stand_Jet.png"
heroStand = true;
heroY = heroY + 10;
downPressed = false;
}
else
{
downPressed = false;
heroStand = false;
}
}
displayScoreArea();
drawHero(heroX,heroY);
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
requestAnimationFrame(moveHero);
}
//Level Setter
var level = 2;
function setLvl()
{
if(level == 1)
{
canvas.style = "background: url('Level 1.png')";
levelKillCounter = 3;
}
else if(level == 2)
{
canvas.style = "background: url('Level 2.png')";
monster1.src = "Monster3_Right.png"
monster2.src = "Monster3_Right.png"
}
else if(level == 3)
{
canvas.style = "background: url('Level 3.png')";
}
}
var gameAudio = new Audio();
gameAudio.src = "Dungeon Theme.mp3"
function animation()
{
setTimeout(() => {
//animation code goes into this anonymous function handler
requestAnimationFrame(animation);
//clear the whole canvas area
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveHero();
drawMonster1();
drawMonster2();
drawMonster3();
drawKey();
drawBullet(bulletX,bulletY);
monsterAnimate();
setLvl();
heroY = heroY + gravity;
if(moveBullet)
{
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if(s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png")
{
bulletX +=20;
}
if(s == "Protagenist_Left_Jet.png")
{
bulletX -=20;
}
if(bulletX >= canvas.width)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
if(bulletX <= 0)
{
moveBullet = false;
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
console.log(getDistanceHit1());
if (getDistanceHit1() <= 30 ||
getDistanceHit2() <= 30 ||
getDistanceHit3() <= 30 )
{
//Delete Monster
if(getDistanceHit1() <= 30)
{
m1X = 1000;
m1Y = 1000;
}
if(getDistanceHit2() <= 30)
{
m2X = 1000;
m2Y = 1000;
}
if(getDistanceHit3() <= 30)
{
m3X = 1000;
m3Y = 1000;
}
//increase the hit count
killCounter++;
//we have a hit
moveBullet = false;
//play the hitAudio
hitAudio.play();
//Reset Bullet
bulletX = canvas.width + 50
bulletY = canvas.height +50;
}
}
if(killCounter == 3)
{
keyX = canvas.width / 2;
keyY = 150;
}
if(getDistanceKey() <= 10)
{
keyCounter = 1;
keyX = 1000;
keyY = 1000;
}
//level progression flow - check of level objectives are met
if (level == 1 && keyCounter == 1 && heroX >= 700 & heroY >= 50) {
alert("Level 1 completed. Starting Level 2...");
level = 2;
killCounter = 0; //reset
keyCounter = 0;//reset
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
}
else if (level == 2 && keyCounter == 1 && heroX == 700 & heroY == 50) {
alert("Level 2 completed. Starting Level 3...");
level = 3;
killCounter = 0; //reset
keyCounter = 0;//reset
}
else if (level == 3 && currentLevelHits == 4) {
//last level
var playAgain = confirm("Game completed. Play again?");
if (playAgain)
window.location.reload(true); //force reload
else
stopAnimation = true;
}
//gameAudio.play();
displayScoreArea();
hitBottom();
},100)
}
m1X = 700;
m1Y = 370;
m2X = 100;
m2Y = 320;
m3X = 100;
m3Y = 170;
function monsterAnimate()
{
//Movement for level 1
if(level == 1)
{
if(m1MoveLeft)
{
m1X -= 10
}
else if(!m1MoveLeft)
{
m1X += 10
}
if(m2MoveRight)
{
m2X += 10
}
else if(!m2MoveRight)
{
m2X -= 10
}
if(m3MoveRight)
{
m3X +=10
}
else if(!m3MoveRight)
{
m3X -= 10
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 310)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 310)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
//Movement for level 2
if(level == 2)
{
if(m1MoveLeft)
{
m1X -= 20
}
else if(!m1MoveLeft)
{
m1X += 20
}
if(m2MoveRight)
{
m2X += 20
}
else if(!m2MoveRight)
{
m2X -= 20
}
if(m3MoveRight)
{
m3X +=20
}
else if(!m3MoveRight)
{
m3X -= 20
}
if(m1X == 420)
{
m1MoveLeft = false;
monster1.src ="Monster 1_Right.png"
}
else if(m1X == 700)
{
m1MoveLeft = true;
monster1.src ="Monster1_Left.png"
}
if(m2X == 600)
{
m2MoveRight = false;
monster2.src ="Monster2_left.png"
}
else if(m2X == 100)
{
m2MoveRight = true;
monster2.src ="Monster 2_Right.png"
}
if(m3X == 500)
{
m3MoveRight = false;
monster3.src ="Monster 3_left.png"
}
else if(m3X == 100)
{
m3MoveRight = true;
monster3.src ="Monster3_Right.png"
}
}
}
// Create gradient
var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
gradient.addColorStop("0", "black");
gradient.addColorStop("0.5", "red");
gradient.addColorStop("1.0", "white");
//Draw Score Area
function displayScoreArea() {
ctx.font = "40px Arial";
ctx.strokeStyle = gradient;
ctx.fillStyle = gradient;
ctx.strokeText(killCounter, 380, 60);
ctx.strokeText(life, 65, 45);
ctx.strokeText(keyCounter, 65, 90);
}
animation();
function moveup()
{
upPressed = true;
}
function movedown()
{
downPressed = true;
}
function moveright()
{
rightPressed = true;
}
function moveleft()
{
leftPressed = true;
}
function shootGun()
{
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
console.log("BulletX = " + bulletX);
}
</script>
<div style="text-align:center;width:900px;">
<button style="width: 100px; height: 60px;" onclick="moveup()">UP</button><br><br>
<button style="width: 100px; height: 60px;" onclick="moveleft()">LEFT</button>
<button style="width: 100px; height: 60px; margin-left: 20px;" onclick="moveright()">RIGHT</button><br><br>
<button style="width: 100px; height: 60px;" onclick="movedown()">DOWN</button>
<button style="width: 100px; height: 60px;" onclick="shootGun()">SHOOT</button>
</div>
</body>
</html>
Using objects would be one (of many) steps in the right direction. Even without them, you could:
In your bullet variable creation
...
//Bullet Attribute
let bulletX;
let bulletY;
let bulletVelocity;
...
In your hero control function, where the firing action currently takes place, initialize your bullet properties once
...
//Keyboard Cotrolls
function heroControl(event) { //event handler function
if (event.keyCode == 32) { //SPACE BAR PRESSED - fire gun
moveBullet = true;
fireAudio.play();
bulletX = heroX + 10;
bulletY = heroY + (heroHeight / 2);
// Initialize bullet velocity
let s = heroPic.src.substring(heroPic.src.lastIndexOf("/") + 1);
//alert(s);
if (s == "Protagenist_Right_Jet.png" || s == "Protagenist_Stand_Jet.png") {
bulletVelocity = 20;
} else {
bulletVelocity = -20;
}
...
In your animation function, where this currently takes place, update your bullet position according to its velocity
...
if (moveBullet) {
bulletX += bulletVelocity;
if (bulletX >= canvas.width) {
...
There are lots of things I would refactor in your current setup, but this should get you moving on your current problem.
And a quick example of a very simple object:
// create with key: value pairs
let bullet = {
x: 0,
y: 0,
velocity: 0,
};
// Access or set properties using dot notation
bullet.x = heroX + 10;
bullet.y = heroY + (heroHeight / 2);

canvas doesn't work when other div are added

I got this problem: I found a very cool pen on codepen, I take it, modified, but when I put this in my html page doesn't work with other divs.
Here the pen https://jsfiddle.net/jtz21sz3/
<canvas id="stage" width="400" height="400">
<p>Your browser doesn't support canvas.</p>
</canvas>
everything work, but when i try to insert a sticky menu in the top the canvas draws the circle, but I can't drag them.
https://jsfiddle.net/Lp9w34sd/1/
<div class="sticky-menu-wrapper">
<nav class="main-menu clear">
<div class="menu-menu-1-container"><ul id="menu-menu-1" class="menu" style="text-align:center">
<li id="menu-item-135" class="menu-item menu-item-type-custom menu-item-object-custom" style=" text-align:left; float: left; padding-top:16px;"><a>RELEASE</a></li>
</ul></div>
</nav>
</div>
<canvas id="stage" width="400" height="400">
<p>Your browser doesn't support canvas.</p>
</canvas>
Any idea how to fix it?
Change function getMouseXY(e) { to this
function getMouseXY(e) {
mouseX = e.offsetX;
mouseY = e.offsetY;
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
}
Just add position:absolute (or fixed) to the nav.
var stage = document.getElementById('stage');
var browserX = window.screenX;
var browserY = window.screenY;
var balls = [];
var total = 6;
var currentDrag = null;
var mouseX = 0;
var mouseY = 0;
var stageWidth = $(document).width();
var stageHeight = $(document).height();
stage.width = stageWidth;
stage.height = stageHeight;
var IE = document.all ? true : false;
if (!IE) document.addEventListener(Event.MOUSEMOVE, getMouseXY, false);
document.onmousemove = getMouseXY;
window.onresize = function(event) {
stage.width = 10;
stage.height = 10;
stageWidth = $(document).width();
stageHeight = $(document).height();
stage.width = stageWidth;
stage.height = stageHeight;
}
generate();
var drawingCanvas = document.getElementById('stage');
if (drawingCanvas.getContext) {
var context = drawingCanvas.getContext('2d');
setInterval(render, 20);
}
jQuery(document).ready(function() {
$(document).mousedown(function(e) {
onMouseDown();
});
$(document).mouseup(function(e) {
onMouseUp();
});
})
function onMouseDown() {
var j = balls.length;
while (--j > -1) {
var dx = mouseX - balls[j].x;
var dy = mouseY - balls[j].y;
var dist = Math.sqrt(dx * dx + dy * dy);
if (dist < balls[j].size / 2) {
currentDrag = balls[j];
currentDrag.dragging = true;
return;
}
}
}
function onMouseUp() {
if (currentDrag != null) currentDrag.dragging = false;
}
function generate() {
for (var i = 0; i < total; i++) {
var ball = {};
ball.color = "#" + genHex();
ball.bounce = .5 + (Math.random() * .5);
ball.vx = Math.random() * 50 - 25;
ball.vy = Math.random() * 50 - 25;
ball.size = 75 - (ball.bounce * 25);
ball.x = Math.random() * stageWidth;
ball.y = Math.random() * stageHeight;
balls[balls.length] = ball;
}
}
function genHex() {
colors = new Array(14)
colors[0] = "0"
colors[1] = "1"
colors[2] = "2"
colors[3] = "3"
colors[4] = "4"
colors[5] = "5"
colors[5] = "6"
colors[6] = "7"
colors[7] = "8"
colors[8] = "9"
colors[9] = "a"
colors[10] = "b"
colors[11] = "c"
colors[12] = "d"
colors[13] = "e"
colors[14] = "f"
digit = new Array(5)
color = ""
for (i = 0; i < 6; i++) {
digit[i] = colors[Math.round(Math.random() * 14)]
color = color + digit[i]
}
return color;
}
function render() {
var isChange = (browserX != window.screenX || browserY != window.screenY);
if (isChange) {
var diffX = browserX - window.screenX;
browserX = window.screenX;
var diffY = browserY - window.screenY;
browserY = window.screenY;
}
var j = balls.length;
while (--j > -1) {
update(balls[j]);
if (isChange) {
balls[j].vx += (diffX * .05);
balls[j].vy += (diffY * .1);
}
}
draw();
}
function draw() {
context.clearRect(0, 0, stageWidth, stageHeight);
var i = balls.length;
while (--i > -1) {
context.fillStyle = balls[i].color;
context.beginPath();
context.arc(balls[i].x, balls[i].y, balls[i].size, 0, Math.PI * 2, true);
context.closePath();
context.fill();
}
}
function update(ball) {
collisionCheck();
var gravity = 0;
var drag = .98;
if (ball.dragging) {
ball.vx = ball.x - ball.ox;
ball.vy = ball.y - ball.oy;
ball.ox = ball.x;
ball.oy = ball.y;
ball.x = mouseX;
ball.y = mouseY;
if ((ball.x + ball.size) > stageWidth) {
ball.x = stageWidth - ball.size;
} else if ((ball.x - ball.size) < 0) {
ball.x = 0 + ball.size;
}
if ((ball.y + ball.size) > stageHeight) {
ball.y = stageHeight - ball.size;
} else if ((ball.y - ball.size) < 0) {
ball.y = 0 + ball.size;
}
} else {
ball.x += ball.vx;
ball.y += ball.vy;
if ((ball.x + ball.size) > stageWidth) {
ball.x = stageWidth - ball.size;
ball.vx = -ball.vx * ball.bounce;
} else if ((ball.x - ball.size) < 0) {
ball.x = 0 + ball.size;
ball.vx = -ball.vx * ball.bounce;
}
if ((ball.y + ball.size) > stageHeight) {
ball.y = stageHeight - ball.size;
ball.vy = -ball.vy * ball.bounce;
} else if ((ball.y - ball.size) < 0) {
ball.y = 0 + ball.size;
ball.vy = -ball.vy * ball.bounce;
}
ball.vx = ball.vx * drag;
ball.vy = ball.vy * drag + gravity;
}
}
function collisionCheck() {
var spring = .5;
for (var i = 0; i < (total - 1); ++i) {
var ball0 = balls[i];
for (var j = i + 1; j < total; ++j) {
var ball1 = balls[j];
var dx = ball1.x - ball0.x;
var dy = ball1.y - ball0.y;
var dist = Math.sqrt(dx * dx + dy * dy);
var minDist = ball0.size + ball1.size;
if (dist < minDist) {
var angle = Math.atan2(dy, dx);
var tx = ball0.x + dx / dist * minDist;
var ty = ball0.y + dy / dist * minDist;
var ax = (tx - ball1.x);
var ay = (ty - ball1.y);
ball0.x -= ax;
ball0.y -= ay;
ball1.x += ax;
ball1.y += ay;
ball0.vx -= (ax * spring);
ball0.vy -= (ay * spring);
ball1.vx += (ax * spring);
ball1.vy += (ay * spring);
}
}
}
}
function getMouseXY(e) {
if (IE) {
mouseX = event.clientX + document.body.scrollLeft
mouseY = event.clientY + document.body.scrollTop
} else {
mouseX = e.pageX
mouseY = e.pageY
}
if (mouseX < 0) {
mouseX = 0;
}
if (mouseY < 0) {
mouseY = 0;
}
return true;
}
#stage { margin:0; padding:0; background-color:#DDD; }
.sticky-menu-wrapper {
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sticky-menu-wrapper">
<nav class="main-menu clear">
<div class="menu-menu-1-container"><ul id="menu-menu-1" class="menu" style="text-align:center">
<li id="menu-item-135" class="menu-item menu-item-type-custom menu-item-object-custom" style=" text-align:left; float: left; padding-top:16px;"><a>RELEASE</a></li>
</ul></div>
</nav>
</div>
<div>
<canvas id="stage" width="400" height="400">
<p>Your browser doesn't support canvas.</p>
</canvas>
</div>

How do you make multiple rectangles in js with on obj? And how do you make them on different x and y axises?

this is my js
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys =[];
var width = 1575,
height = 700,
speed = 10,
score1 = 0,
NUMFOOD = 10,
running = true,
i = 0;
var requestAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
var randomXSpawn = Math.random() * (width - 8);
var randomYSpawn = Math.random() * (height - 8);
function gameObj(x,y,width,height) {
this.x=x;
this.y=y;
this.width=width;
this.height=height;
};
var player1 = new gameObj(0,0,10,10);
var player2 = new gameObj(0, 700-10,10,10);
var food = new gameObj(randomXSpawn,randomYSpawn,3,3);
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
/*
keys
up-38
down-40
right-39
left-37
w-87
s-83
a-65
d-68
y-89
h-72
g-71
j-74
5-101
2-98
1-97
3-99
*/
function game(){
update();
render();
}
function update(){
if(keys[87]) player1.y-=speed;
if(keys[83]) player1.y+=speed;
if(keys[65]) player1.x-=speed;
if(keys[68]) player1.x+=speed;
if(player1.x <0) player1.x=0;
if(player1.y <0) player1.y=0;
if(player1.x >= width - player1.width) player1.x = width - player1.width;
if(player1.y >= height - player1.height) player1.y = height - player1.height;
if(collision(player1, food)){
playerColl1 = true;
process(player1, score1);
console.log("collision");
}
console.log(player1.x, player1.y);
}
function process(player){
score1++;
food.x = Math.random() * (width - 8);
food.y = Math.random() * (height - 8);
if(score1 >= player.width){
player.width++;
player.height++;
if(speed >= 1){
speed = speed - 0.1;
if(speed <= 2){
speed = 2;
}
}
}
}
function render(){
context.clearRect(0,0,width,height);
context.fillStyle = "black";
context.fillRect(width/2 - 1,0,1,height);
context.fillStyle = "blue";
context.fillRect(player1.x, player1.y, player1.width, player1.height);
context.fillStyle = "red";
while(NUMFOOD > i){
food++;
}
context.fillRect(food.x, food.y, food.width, food.height);
context.fillStyle = "black";
context.font = "bold 30px helvetica";
context.fillText(score1, 10,30);
}
function collision(first, second){
return !(first.x > second.x + second.width ||
first.x + first.width < second.x ||
first.y > second.y + second.height||
first.y + first.height < second.y||
second.x > first.x + first.width ||
second.x + second.width < first.x ||
second.y > first.y + first.height||
second.y + second.height < first.y);
}
function animate() {
if (running) {
game();
}
requestAnimFrame(animate);
}
animate();
this is my html
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Game</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<canvas id="mainCanvas" height="700" width="1575"></canvas>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
this is my css
#mainCanvas{
outline: 1px solid black;
background-color: #bcbcbc;
}
I dont know why i cant make multiple rectangles. can someone pls help me any help at all is appreciated. I am trying to use the while loop but it wont work. I am trying to make multiple food(red squares) for my player to eat(blue square)
If i understand correctly, you are trying to have multiple food items that the players can collect.
try updating your js with this. I added comments at the places that i modified:
var canvas = document.getElementById("mainCanvas");
var context = canvas.getContext("2d");
var keys =[];
var width = 1575,
height = 700,
speed = 10,
score1 = 0,
NUMFOOD = 10,
running = true,
i = 0;
var requestAnimFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function gameObj(x,y,width,height) {
this.x=x;
this.y=y;
this.width=width;
this.height=height;
};
var player1 = new gameObj(0,0,10,10);
var player2 = new gameObj(0, 700-10,10,10);
// create a list of food items
var foods = [];
for (var i=0; i< NUMFOOD; i++){
foods[i]=new gameObj( Math.random() * (width - 8), Math.random() * (height- 8),3,3);
}
window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false);
window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false);
/*
keys
up-38
down-40
right-39
left-37
w-87
s-83
a-65
d-68
y-89
h-72
g-71
j-74
5-101
2-98
1-97
3-99
*/
function game(){
update();
render();
}
function update(){
if(keys[87]) player1.y-=speed;
if(keys[83]) player1.y+=speed;
if(keys[65]) player1.x-=speed;
if(keys[68]) player1.x+=speed;
if(player1.x <0) player1.x=0;
if(player1.y <0) player1.y=0;
if(player1.x >= width - player1.width) player1.x = width - player1.width;
if(player1.y >= height - player1.height) player1.y = height - player1.height;
//loop over list of food and check if any hits
for (var i=0; i< NUMFOOD; i++){
if(collision(player1, foods[i])){
playerColl1 = true;
// pass food object that has been hit to process
process(player1, score1, foods[i]);
console.log("collision");
}
}
console.log(player1.x, player1.y);
}
function process(player, score1, food){
score1++;
food.x = Math.random() * (width - 8);
food.y = Math.random() * (height - 8);
if(score1 >= player.width){
player.width++;
player.height++;
if(speed >= 1){
speed = speed - 0.1;
if(speed <= 2){
speed = 2;
}
}
}
}
function render(){
context.clearRect(0,0,width,height);
context.fillStyle = "black";
context.fillRect(width/2 - 1,0,1,height);
context.fillStyle = "blue";
context.fillRect(player1.x, player1.y, player1.width, player1.height);
context.fillStyle = "red";
// render all food items
for (var i=0; i< NUMFOOD; i++){
context.fillRect(foods[i].x, foods[i].y, foods[i].width, foods[i].height);
}
context.fillStyle = "black";
context.font = "bold 30px helvetica";
context.fillText(score1, 10,30);
}
function collision(first, second){
return !(first.x > second.x + second.width ||
first.x + first.width < second.x ||
first.y > second.y + second.height||
first.y + first.height < second.y||
second.x > first.x + first.width ||
second.x + second.width < first.x ||
second.y > first.y + first.height||
second.y + second.height < first.y);
}
function animate() {
if (running) {
game();
}
requestAnimFrame(animate);
}
animate();

keydown controls for animation

<html>
<header>
<link href='css.css' rel='stylesheet'>
<meta charset="UTF-8">
<title> moving box </title>
<script type= 'text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100,
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth){
mx = -4;
}
if (rectangle.x < 0){
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight){
my = -4;
}
if (rectangle.y < 0){
my = 4;
}
}
function keydowncontrol(){
if (e == 37){
mx = -1;
my = 0;
}
if (e == 38){
mx = 0;
my = -1;
}
if (e == 39){
mx = 1;
my = 0;
}
if (e == 40){
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
function init() {
checkmx();
checkmy();
window.onkeydown = keydowncontrol();// how can does this notice the key pressed
draw();
}
</script>
</header>
<body onload='setInterval(init,10)'>
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>
I am trying to animate a box. I'm not sure how the window.onkeydown and event.keycode work. My goal is to have the mx and my variables change depending on the keys pressed. Should keydowncontrol() be in the draw() function or init() function?
Try this:
<html>
<head>
<link href='css.css' rel='stylesheet' />
<meta charset="UTF-8" />
<title>Moving box</title>
<script type='text/javascript'>
var rectangle = {
x: 100,
y: 100,
width: 100,
height: 100
};
var mx = 4;
var my = 4;
var cheight = 700;
var cwidth = 700;
var e = event.keyCode;
function checkmx() {
if (rectangle.x + 100 > cwidth) {
mx = -4;
}
if (rectangle.x < 0) {
mx = 4;
}
}
function checkmy() {
if (rectangle.y + 100 > cheight) {
my = -4;
}
if (rectangle.y < 0) {
my = 4;
}
}
function keydowncontrol(e) {
//alert(e);
if (e.keyCode == 37) {
mx = -1;
my = 0;
}
if (e.keyCode == 38) {
mx = 0;
my = -1;
}
if (e.keyCode == 39) {
mx = 1;
my = 0;
}
if (e.keyCode == 40) {
mx = 0;
my = 1;
}
//if (e == 35){
//mx = 0
//mx = 0
//}
}
function draw() {
checkmx();
checkmy();
//keydowncontrol();
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var nextx = rectangle.x + mx;
var nexty = rectangle.y + my;
rectangle.x = nextx
rectangle.y = nexty
ctx.clearRect(0, 0, cwidth, cheight);
ctx.beginPath();
ctx.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
ctx.fillStyle = '#FF0000';
ctx.fill();
ctx.stroke();
}
//document.attachEvent("onkeypress", keydowncontrol);
</script>
</head>
<body onload='setInterval(draw, 10)' onkeydown="keydowncontrol(event)">
<canvas id="canvas" width="700" height="700"></canvas>
</body>
</html>

Categories