how to use canvas in JavaScript flappy bird code - javascript
I have a working flappy bird code but I was told to use canvas instead. I've tried to read other flappy bird codes but they were very different than mine so every time I tried to apply their codes it didn't work. How can I change my code so the js will contain the build of the canvas and then I can call the game on canvas in the html?
Here is my code snippet:
var bird;
var pole1;
var pole2;
var scoreSpan;
var speedSpan;
var speed;
var score;
var flapping;
var playing;
var scoreUpdated;
var gameArea;
var restartBtn;
var containerWidth;
var containerHeight;
function load() {
bird = document.getElementById("bird")
poles = document.querySelectorAll(".pole")
pole1 = document.getElementById("pole-1")
pole2 = document.getElementById("pole-2")
scoreSpan = document.getElementById("score")
speedSpan = document.getElementById("speed")
gameArea = document.getElementById("game-area");
restartBtn = document.getElementById("restart-btn");
containerWidth = gameArea.clientWidth;
containerHeight = gameArea.clientHeight;
gameArea.addEventListener("mousedown", function (e) {
if (playing) {
flapping = true;
}
});
gameArea.addEventListener("mouseup", function (e) {
if (playing) {
flapping = false;
}
});
}
function restart() {
restartBtn.removeEventListener('click', restart);
speed = 2;
score = 0;
scoreUpdated = false;
flapping = false;
playing = true;
speedSpan.textContent = speed;
scoreSpan.textContent = score;
poles.forEach((pole) => {
pole.style.right = 0;
});
bird.style.top = 20 + "%";
gameLoop();
}
function update() {
var polesCurrentPos = parseFloat(window.getComputedStyle(poles[0]).getPropertyValue("right"));
if (polesCurrentPos > containerWidth * 0.85) {
if (!scoreUpdated) {
score += 1;
scoreUpdated = true;
}
scoreSpan.textContent = score;
}
if (polesCurrentPos > containerWidth) {
var newHeight = parseInt(Math.random() * 100);
pole1.style.height = 100 + newHeight + "px";
pole2.style.height = 100 - newHeight + "px";
polesCurrentPos = 0;
speed += 0.25;
speedSpan.textContent = parseInt(speed);
scoreUpdated = false;
}
poles.forEach((pole) => {
pole.style.right = polesCurrentPos + speed + "px";
});
let birdTop = parseFloat(window.getComputedStyle(bird).getPropertyValue("top"));
if (flapping) {
bird.style.top = birdTop + -2 + "px";
} else if (birdTop < containerHeight - bird.clientHeight) {
bird.style.top = birdTop + 2 + "px";
}
if (collision(bird, pole1) || collision(bird, pole2) || birdTop <= 0 || birdTop > containerHeight - bird.clientHeight) {
gameOver();
}
}
function gameOver() {
window.console.log("game over");
playing = false;
restartBtn.addEventListener('click', restart);
}
function gameLoop() {
update();
if (playing) {
requestAnimationFrame(gameLoop);
}
}
function collision(gameDiv1, gameDiv2) {
let left1 = gameDiv1.getBoundingClientRect().left;
let top1 = gameDiv1.getBoundingClientRect().top;
let height1 = gameDiv1.clientHeight;
let width1 = gameDiv1.clientWidth;
let bottom1 = top1 + height1;
let right1 = left1 + width1;
let left2 = gameDiv2.getBoundingClientRect().left;
let top2 = gameDiv2.getBoundingClientRect().top;
let height2 = gameDiv2.clientHeight;
let width2 = gameDiv2.clientWidth;
let bottom2 = top2 + height2;
let right2 = left2 + width2;
if (bottom1 < top2 || top1 > bottom2 || right1 < left2 || left1 > right2)
return false;
return true;
}
document.addEventListener("keydown", function (e) {
var key = e.key;
if (key === " " && playing) {
flapping = true;
}
});
document.addEventListener("keyup", function (e) {
e.preventDefault();
var key = e.key;
if (key === " " && playing) {
flapping = false;
}
});
load();
restart();
#game {
font-family: David, cursive, sans-serif;
text-align: center;
}
#instructions {
text-align: center;
}
#game-area {
margin: auto;
position: relative;
width: 400px;
height: 300px;
border: 2px solid green;
background-color: deepskyblue;
overflow: hidden;
}
#bird {
position: absolute;
background: url('https://usercontent.one/wp/compucademy.net/wp-content/uploads/2020/11/robbybird.png');
height: 27px;
width: 42px;
background-size: contain;
background-repeat: no-repeat;
top: 20%;
left: 15%;
}
.pole {
position: absolute;
height: 100px;
width: 30px;
background-color: green;
right: 0px;
}
#pole-1 {
top: 0;
}
#pole-2 {
bottom: 0;
}
#game-info {
margin: 5px;
font-size: 18px;
}
#game-info p {
display: inline;
padding: 20px;
}
#restart-btn {
padding: 5px 10px;
background-color: green;
color: white;
font-size: 18px;
border: none;
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stav Levy - Flappy Bird</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css" media="screen" />
<script src="game.js" defer></script>
</head>
<body>
<div id="game">
<div id="game-area">
<div id="bird"></div>
<div class="pole" id="pole-1"></div>
<div class="pole" id="pole-2"></div>
</div>
<div id="game-info">
<p>Score:<span id="score">0</span></p>
<button id="restart-btn">Restart</button>
<p>Speed:<span id="speed">2</span></p>
</div>
</div>
</body>
</html>
var bird;
var pole1;
var pole2;
var scoreSpan;
var speedSpan;
var highSpan;
var speed;
var score;
var high;
var flapping;
var playing;
var scoreUpdated;
var gameArea;
var restartBtn;
var containerWidth;
var containerHeight;
function load() {
high = 0;
bird = document.getElementById("bird")
poles = document.querySelectorAll(".pole")
pole1 = document.getElementById("pole-1")
pole2 = document.getElementById("pole-2")
scoreSpan = document.getElementById("score")
speedSpan = document.getElementById("speed")
highSpan = document.getElementById("high")
gameArea = document.getElementById("game-area");
restartBtn = document.getElementById("restart-btn");
containerWidth = gameArea.clientWidth;
containerHeight = gameArea.clientHeight;
gameArea.addEventListener("mousedown", function (e) {
if (playing) {
flapping = true;
}
});
gameArea.addEventListener("mouseup", function (e) {
if (playing) {
flapping = false;
}
});
}
function restart() {
restartBtn.removeEventListener('click', restart);
if(score >= high){
high = score;
}
speed = 2;
score = 0;
scoreUpdated = false;
flapping = false;
playing = true;
speedSpan.textContent = speed;
scoreSpan.textContent = score;
highSpan.textContent = high;
poles.forEach((pole) => {
pole.style.right = 0;
});
bird.style.top = 20 + "%";
gameLoop();
}
function update() {
var polesCurrentPos = parseFloat(window.getComputedStyle(poles[0]).getPropertyValue("right"));
if (polesCurrentPos > containerWidth * 0.85) {
if (!scoreUpdated) {
score += 1;
scoreUpdated = true;
}
scoreSpan.textContent = score;
if(score >= high){
high = score;
highSpan.textContent = high;
}
}
if (polesCurrentPos > containerWidth) {
var newHeight = parseInt(Math.random() * 100);
pole1.style.height = 100 + newHeight + "px";
pole2.style.height = 100 - newHeight + "px";
polesCurrentPos = 0;
speed += 0.25;
speedSpan.textContent = parseInt(speed);
scoreUpdated = false;
}
poles.forEach((pole) => {
pole.style.right = polesCurrentPos + speed + "px";
});
let birdTop = parseFloat(window.getComputedStyle(bird).getPropertyValue("top"));
if (flapping) {
bird.style.top = birdTop + -2 + "px";
} else if (birdTop < containerHeight - bird.clientHeight) {
bird.style.top = birdTop + 2 + "px";
}
if (collision(bird, pole1) || collision(bird, pole2) || birdTop <= 0 || birdTop > containerHeight - bird.clientHeight) {
gameOver();
}
}
function gameOver() {
window.console.log("Game Over!:(");
playing = false;
restartBtn.addEventListener('click', restart);
}
function gameLoop() {
update();
if (playing) {
requestAnimationFrame(gameLoop);
}
}
function collision(gameDiv1, gameDiv2) {
let left1 = gameDiv1.getBoundingClientRect().left;
let top1 = gameDiv1.getBoundingClientRect().top;
let height1 = gameDiv1.clientHeight;
let width1 = gameDiv1.clientWidth;
let bottom1 = top1 + height1;
let right1 = left1 + width1;
let left2 = gameDiv2.getBoundingClientRect().left;
let top2 = gameDiv2.getBoundingClientRect().top;
let height2 = gameDiv2.clientHeight;
let width2 = gameDiv2.clientWidth;
let bottom2 = top2 + height2;
let right2 = left2 + width2;
if (bottom1 < top2 || top1 > bottom2 || right1 < left2 || left1 > right2)
return false;
return true;
}
document.addEventListener("keydown", function (e) {
var key = e.key;
if (key === " " && playing) {
flapping = true;
}
});
document.addEventListener("keyup", function (e) {
e.preventDefault();
var key = e.key;
if (key === " " && playing) {
flapping = false;
}
});
var myGameArea = {
canvas : document.createElement("div"),
game : document.getElementById("game"),
gamearea : document.createElement("div"),
gameinfo : document.createElement("div"),
bird : document.createElement("div"),
pole1 : document.createElement("div"),
pole2 : document.createElement("div"),
score : document.createElement("p"),
scores : document.createElement("span"),
speed : document.createElement("p"),
speeds : document.createElement("span"),
high : document.createElement("p"),
highs : document.createElement("span"),
restart : document.createElement("button"),
start : function() {
this.canvas.style = "font-family: David, cursive, sans-serif;text-align: center;";
this.canvas.width = 504;
this.canvas.height = 341;
this.game.appendChild(this.canvas);
this.gamearea.style = "margin: auto;position: relative;width: 400px;height: 300px;border: 2px solid green;background-color: deepskyblue;overflow: hidden;";
this.gamearea.id = "game-area";
this.canvas.appendChild(this.gamearea);
this.gameinfo.style = "margin: 5px;font-size: 18px;";
this.gameinfo.id = "game-info";
this.canvas.appendChild(this.gameinfo);
this.bird.style = "position: absolute;background:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAABkCAYAAACPbHLzAAAABmJLR0QArgB4ACK51uKEAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4AobCCQTbH2I3QAAAfZJREFUeNrt3dFto0AUQFGIUgkd0Y1TgVON3ZFbmfz4IwlIJPAeA55zJP+stNoV3H0zDNam6wCOrt/zDytdV1zy6jc8/Z6/ucyIClEhKhAVokJUICpEhahAVIiKl+CFcmued6Dv8+69SdVqWyXvH7iohGX5I2b5m4QQuByaVIRPLVERHpblz/IXvhyKqpL7ZZj82vj5OExUW8J6d3vrxDRepwHdu2G/uP64HGaeZ4VNqpY/t8tQSukWP7fLkPf3KOs+ojpxUOlhlfywPP0R/nQoqkqb8iXj9bHq9+0R1lJcotrJ3Mb8VaeWqAgPS1SEL4eiYtdNvCMFRwqrjhycqLNZ1VN3J+rnPVH/z0GoF8qVzqxm3/197PDur+RPJVFVjuvHWdbBvqWwdokTVXOPafl7JRt1wjfeoiL8CU5UYgrfAolKSOG8phGUqDi+2agO/71kzhfV97hcIjZH9TskU4u0PZWwSNmom1qkPf2Ji/CoLImkRWVqkRKVqUVaVKYWKVGZWqRFZWqJKpW4RJUal8stKhAVoqKFqOx7MKkQFaICUSEqRAWiQlSICkSFqBAViIo0i/8BVug3F3oX/AA3vK8eVWhoohJVeGiiElV4aKISVXhkfuJDE1F5+kNUiApRgagQFaICUSEqRAWiQlSICkQFAAAARPkCSGysXZ/O3oIAAAAASUVORK5CYII=');height: 27px;width: 42px;background-size: contain;background-repeat: no-repeat;top: 20%;left: 15%;";
this.bird.id = "bird";
this.gamearea.appendChild(this.bird);
this.pole1.style = "position: absolute;height: 100px;width: 30px;background-color: green;right: 0px;top: 0;";
this.pole1.id = "pole-1";
this.pole1.className = "pole";
this.gamearea.appendChild(this.pole1);
this.pole2.style = "position: absolute;height: 100px;width: 30px;background-color: green;right: 0px; bottom: 0;";
this.pole2.id = "pole-2";
this.pole2.className = "pole";
this.gamearea.appendChild(this.pole2);
this.score.style = "display: inline;padding: 20px;";
var s1 = document.createTextNode("Score: ");
this.score.appendChild(s1);
this.gameinfo.appendChild(this.score);
this.restart.id = "restart-btn";
this.restart.style = "padding: 5px 10px;background-color: green;color: white;font-size: 18px;border: none;cursor: pointer;outline: none;";
var restartbtn = document.createTextNode("Restart");
this.restart.appendChild(restartbtn);
this.gameinfo.appendChild(this.restart);
this.speed.style = "display: inline;padding: 20px;";
var s2 = document.createTextNode("Speed: ");
this.speed.appendChild(s2);
this.gameinfo.appendChild(this.speed);
this.high.style = "display: inline;padding: 20px;";
var s3 = document.createTextNode("High Score: ");
this.high.appendChild(s3);
this.gameinfo.appendChild(this.high);
this.scores.id = "score";
var s1s = document.createTextNode("0");
this.scores.appendChild(s1s);
this.score.appendChild(this.scores);
this.speeds.id = "speed";
var s2s = document.createTextNode("2");
this.speeds.appendChild(s2s);
this.speed.appendChild(this.speeds);
this.highs.id = "high";
var s3s = document.createTextNode("0");
this.highs.appendChild(s3s);
this.high.appendChild(this.highs);
}
}
myGameArea.start();
load();
restart();
#instructions {
text-align: center;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Stav Levy - Flappy Bird</title>
<link rel="stylesheet" type="text/css" href="stylesheet1.css" media="screen" />
<script src="game.js" defer></script>
</head>
<body>
<div id="game"></div>
</body>
</html>
Added a High score,
You can make this your game.js:
var _0x17f7=['keydown','speeds','key','getComputedStyle','restart-btn','1612485FGBzmk','width','gamearea','top','game-info','button','random','Restart','High\x20Score:\x20','style','pole','className','2unDJtD','speed','div','getElementById','29hUBqcR','querySelectorAll','position:\x20absolute;background:url(\x27data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJUAAABkCAYAAACPbHLzAAAABmJLR0QArgB4ACK51uKEAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4AobCCQTbH2I3QAAAfZJREFUeNrt3dFto0AUQFGIUgkd0Y1TgVON3ZFbmfz4IwlIJPAeA55zJP+stNoV3H0zDNam6wCOrt/zDytdV1zy6jc8/Z6/ucyIClEhKhAVokJUICpEhahAVIiKl+CFcmued6Dv8+69SdVqWyXvH7iohGX5I2b5m4QQuByaVIRPLVERHpblz/IXvhyKqpL7ZZj82vj5OExUW8J6d3vrxDRepwHdu2G/uP64HGaeZ4VNqpY/t8tQSukWP7fLkPf3KOs+ojpxUOlhlfywPP0R/nQoqkqb8iXj9bHq9+0R1lJcotrJ3Mb8VaeWqAgPS1SEL4eiYtdNvCMFRwqrjhycqLNZ1VN3J+rnPVH/z0GoF8qVzqxm3/197PDur+RPJVFVjuvHWdbBvqWwdokTVXOPafl7JRt1wjfeoiL8CU5UYgrfAolKSOG8phGUqDi+2agO/71kzhfV97hcIjZH9TskU4u0PZWwSNmom1qkPf2Ji/CoLImkRWVqkRKVqUVaVKYWKVGZWqRFZWqJKpW4RJUal8stKhAVoqKFqOx7MKkQFaICUSEqRAWiQlSICkSFqBAViIo0i/8BVug3F3oX/AA3vK8eVWhoohJVeGiiElV4aKISVXhkfuJDE1F5+kNUiApRgagQFaICUSEqRAWiQlSICkQFAAAARPkCSGysXZ/O3oIAAAAASUVORK5CYII=\x27);height:\x2027px;width:\x2042px;background-size:\x20contain;background-repeat:\x20no-repeat;top:\x2020%;left:\x2015%;','appendChild','high','getPropertyValue','clientHeight','pole1','margin:\x205px;font-size:\x2018px;','keyup','14553WyuJlp','scores','right','58uchahV','canvas','addEventListener','mousedown','display:\x20inline;padding:\x2020px;','bird','log','console','margin:\x20auto;position:\x20relative;width:\x20400px;height:\x20300px;border:\x202px\x20solid\x20green;background-color:\x20deepskyblue;overflow:\x20hidden;','createTextNode','height','textContent','forEach','restart','game','span','click','416037dSmWSW','removeEventListener','highs','956187VUgTEr','score','position:\x20absolute;height:\x20100px;width:\x2030px;background-color:\x20green;right:\x200px;top:\x200;','pole-2','pole-1','game-area','left','createElement','Game\x20Over!:(','gameinfo','font-family:\x20David,\x20cursive,\x20sans-serif;text-align:\x20center;','start','clientWidth','mouseup','537932frCLSN','preventDefault','18251CLUIcx','pole2','getBoundingClientRect','1872951KVXNxf'];var _0x2cae4b=_0x4911;(function(_0x41a294,_0x5c4e5e){var _0x50bc6c=_0x4911;while(!![]){try{var _0x19b435=-parseInt(_0x50bc6c(0x151))+-parseInt(_0x50bc6c(0x184))*-parseInt(_0x50bc6c(0x187))+parseInt(_0x50bc6c(0x164))+parseInt(_0x50bc6c(0x176))*parseInt(_0x50bc6c(0x14e))+parseInt(_0x50bc6c(0x15f))+-parseInt(_0x50bc6c(0x16a))+parseInt(_0x50bc6c(0x161))*-parseInt(_0x50bc6c(0x17a));if(_0x19b435===_0x5c4e5e)break;else _0x41a294['push'](_0x41a294['shift']());}catch(_0x5e264a){_0x41a294['push'](_0x41a294['shift']());}}}(_0x17f7,0xf1798));var bird,pole1,pole2,scoreSpan,speedSpan,highSpan,speed,score,high,flapping,playing,scoreUpdated,gameArea,restartBtn,containerWidth,containerHeight;function load(){var _0x44043f=_0x4911;high=0x0,bird=document[_0x44043f(0x179)]('bird'),poles=document[_0x44043f(0x17b)]('.pole'),pole1=document[_0x44043f(0x179)](_0x44043f(0x155)),pole2=document['getElementById'](_0x44043f(0x154)),scoreSpan=document[_0x44043f(0x179)](_0x44043f(0x152)),speedSpan=document[_0x44043f(0x179)]('speed'),highSpan=document[_0x44043f(0x179)]('high'),gameArea=document[_0x44043f(0x179)](_0x44043f(0x156)),restartBtn=document[_0x44043f(0x179)](_0x44043f(0x169)),containerWidth=gameArea['clientWidth'],containerHeight=gameArea['clientHeight'],gameArea['addEventListener'](_0x44043f(0x18a),function(_0x416cb1){playing&&(flapping=!![]);}),gameArea['addEventListener'](_0x44043f(0x15e),function(_0x5f38ba){playing&&(flapping=![]);});}function restart(){var _0x3509a2=_0x4911;restartBtn[_0x3509a2(0x14f)]('click',restart),score>=high&&(high=score),speed=0x2,score=0x0,scoreUpdated=![],flapping=![],playing=!![],speedSpan[_0x3509a2(0x148)]=speed,scoreSpan['textContent']=score,highSpan[_0x3509a2(0x148)]=high,poles[_0x3509a2(0x149)](_0x377dd7=>{var _0x3f52a5=_0x3509a2;_0x377dd7['style'][_0x3f52a5(0x186)]=0x0;}),bird['style'][_0x3509a2(0x16d)]=0x14+'%',gameLoop();}function update(){var _0x57cb38=_0x4911,_0x3a5b0e=parseFloat(window[_0x57cb38(0x168)](poles[0x0])['getPropertyValue']('right'));_0x3a5b0e>containerWidth*0.85&&(!scoreUpdated&&(score+=0x1,scoreUpdated=!![]),scoreSpan[_0x57cb38(0x148)]=score,score>=high&&(high=score,highSpan[_0x57cb38(0x148)]=high));if(_0x3a5b0e>containerWidth){var _0x3c31ef=parseInt(Math[_0x57cb38(0x170)]()*0x64);pole1[_0x57cb38(0x173)]['height']=0x64+_0x3c31ef+'px',pole2['style']['height']=0x64-_0x3c31ef+'px',_0x3a5b0e=0x0,speed+=0.25,speedSpan[_0x57cb38(0x148)]=parseInt(speed),scoreUpdated=![];}poles['forEach'](_0xc70738=>{var _0x57a41f=_0x57cb38;_0xc70738['style'][_0x57a41f(0x186)]=_0x3a5b0e+speed+'px';});let _0x4dcb84=parseFloat(window[_0x57cb38(0x168)](bird)[_0x57cb38(0x17f)](_0x57cb38(0x16d)));if(flapping)bird[_0x57cb38(0x173)]['top']=_0x4dcb84+-0x2+'px';else _0x4dcb84<containerHeight-bird[_0x57cb38(0x180)]&&(bird['style']['top']=_0x4dcb84+0x2+'px');(collision(bird,pole1)||collision(bird,pole2)||_0x4dcb84<=0x0||_0x4dcb84>containerHeight-bird[_0x57cb38(0x180)])&&gameOver();}function gameOver(){var _0x5cdeba=_0x4911;window[_0x5cdeba(0x144)][_0x5cdeba(0x18d)](_0x5cdeba(0x159)),playing=![],restartBtn[_0x5cdeba(0x189)](_0x5cdeba(0x14d),restart);}function _0x4911(_0x2133ce,_0x17efe4){_0x2133ce=_0x2133ce-0x144;var _0x17f700=_0x17f7[_0x2133ce];return _0x17f700;}function gameLoop(){update(),playing&&requestAnimationFrame(gameLoop);}function collision(_0x58e8f3,_0x59e939){var _0x51befa=_0x4911;let _0x460ed8=_0x58e8f3[_0x51befa(0x163)]()[_0x51befa(0x157)],_0x5e4638=_0x58e8f3[_0x51befa(0x163)]()[_0x51befa(0x16d)],_0x94d2e6=_0x58e8f3[_0x51befa(0x180)],_0x2163c2=_0x58e8f3[_0x51befa(0x15d)],_0x4a04b9=_0x5e4638+_0x94d2e6,_0x3de9ab=_0x460ed8+_0x2163c2,_0xb5e616=_0x59e939['getBoundingClientRect']()[_0x51befa(0x157)],_0x346e85=_0x59e939[_0x51befa(0x163)]()[_0x51befa(0x16d)],_0x16ac32=_0x59e939['clientHeight'],_0x159223=_0x59e939['clientWidth'],_0x135f86=_0x346e85+_0x16ac32,_0x287884=_0xb5e616+_0x159223;if(_0x4a04b9<_0x346e85||_0x5e4638>_0x135f86||_0x3de9ab<_0xb5e616||_0x460ed8>_0x287884)return![];return!![];}document[_0x2cae4b(0x189)](_0x2cae4b(0x165),function(_0x25ccfd){var _0x4f3bd0=_0x2cae4b,_0x43929f=_0x25ccfd[_0x4f3bd0(0x167)];_0x43929f==='\x20'&&playing&&(flapping=!![]);}),document[_0x2cae4b(0x189)](_0x2cae4b(0x183),function(_0x1f404d){var _0x332edf=_0x2cae4b;_0x1f404d[_0x332edf(0x160)]();var _0x43ba5e=_0x1f404d['key'];_0x43ba5e==='\x20'&&playing&&(flapping=![]);});var myGameArea={'canvas':document['createElement'](_0x2cae4b(0x178)),'game':document['getElementById']('game'),'gamearea':document[_0x2cae4b(0x158)](_0x2cae4b(0x178)),'gameinfo':document[_0x2cae4b(0x158)](_0x2cae4b(0x178)),'bird':document[_0x2cae4b(0x158)](_0x2cae4b(0x178)),'pole1':document['createElement'](_0x2cae4b(0x178)),'pole2':document[_0x2cae4b(0x158)]('div'),'score':document[_0x2cae4b(0x158)]('p'),'scores':document[_0x2cae4b(0x158)](_0x2cae4b(0x14c)),'speed':document[_0x2cae4b(0x158)]('p'),'speeds':document[_0x2cae4b(0x158)](_0x2cae4b(0x14c)),'high':document[_0x2cae4b(0x158)]('p'),'highs':document['createElement'](_0x2cae4b(0x14c)),'restart':document[_0x2cae4b(0x158)](_0x2cae4b(0x16f)),'start':function(){var _0x4c7d56=_0x2cae4b;this[_0x4c7d56(0x188)][_0x4c7d56(0x173)]=_0x4c7d56(0x15b),this['canvas'][_0x4c7d56(0x16b)]=0x1f8,this[_0x4c7d56(0x188)][_0x4c7d56(0x147)]=0x155,this[_0x4c7d56(0x14b)]['appendChild'](this[_0x4c7d56(0x188)]),this[_0x4c7d56(0x16c)][_0x4c7d56(0x173)]=_0x4c7d56(0x145),this['gamearea']['id']=_0x4c7d56(0x156),this[_0x4c7d56(0x188)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x16c)]),this[_0x4c7d56(0x15a)][_0x4c7d56(0x173)]=_0x4c7d56(0x182),this['gameinfo']['id']=_0x4c7d56(0x16e),this[_0x4c7d56(0x188)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x15a)]),this['bird'][_0x4c7d56(0x173)]=_0x4c7d56(0x17c),this[_0x4c7d56(0x18c)]['id']=_0x4c7d56(0x18c),this[_0x4c7d56(0x16c)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x18c)]),this[_0x4c7d56(0x181)]['style']=_0x4c7d56(0x153),this['pole1']['id']=_0x4c7d56(0x155),this[_0x4c7d56(0x181)]['className']='pole',this[_0x4c7d56(0x16c)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x181)]),this[_0x4c7d56(0x162)][_0x4c7d56(0x173)]='position:\x20absolute;height:\x20100px;width:\x2030px;background-color:\x20green;right:\x200px;\x20bottom:\x200;',this[_0x4c7d56(0x162)]['id']=_0x4c7d56(0x154),this['pole2'][_0x4c7d56(0x175)]=_0x4c7d56(0x174),this[_0x4c7d56(0x16c)][_0x4c7d56(0x17d)](this['pole2']),this['score']['style']=_0x4c7d56(0x18b);var _0x460a16=document[_0x4c7d56(0x146)]('Score:\x20');this['score'][_0x4c7d56(0x17d)](_0x460a16),this[_0x4c7d56(0x15a)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x152)]),this[_0x4c7d56(0x14a)]['id']=_0x4c7d56(0x169),this[_0x4c7d56(0x14a)][_0x4c7d56(0x173)]='padding:\x205px\x2010px;background-color:\x20green;color:\x20white;font-size:\x2018px;border:\x20none;cursor:\x20pointer;outline:\x20none;';var _0x3c2ac3=document[_0x4c7d56(0x146)](_0x4c7d56(0x171));this[_0x4c7d56(0x14a)][_0x4c7d56(0x17d)](_0x3c2ac3),this[_0x4c7d56(0x15a)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x14a)]),this[_0x4c7d56(0x177)][_0x4c7d56(0x173)]=_0x4c7d56(0x18b);var _0x185bbb=document[_0x4c7d56(0x146)]('Speed:\x20');this['speed'][_0x4c7d56(0x17d)](_0x185bbb),this[_0x4c7d56(0x15a)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x177)]),this[_0x4c7d56(0x17e)]['style']=_0x4c7d56(0x18b);var _0x56e2ac=document['createTextNode'](_0x4c7d56(0x172));this[_0x4c7d56(0x17e)][_0x4c7d56(0x17d)](_0x56e2ac),this[_0x4c7d56(0x15a)]['appendChild'](this['high']),this[_0x4c7d56(0x185)]['id']=_0x4c7d56(0x152);var _0x2b0f6c=document[_0x4c7d56(0x146)]('0');this[_0x4c7d56(0x185)]['appendChild'](_0x2b0f6c),this['score'][_0x4c7d56(0x17d)](this[_0x4c7d56(0x185)]),this[_0x4c7d56(0x166)]['id']=_0x4c7d56(0x177);var _0x2d4c99=document[_0x4c7d56(0x146)]('2');this[_0x4c7d56(0x166)][_0x4c7d56(0x17d)](_0x2d4c99),this['speed']['appendChild'](this[_0x4c7d56(0x166)]),this['highs']['id']=_0x4c7d56(0x17e);var _0x31e117=document[_0x4c7d56(0x146)]('0');this[_0x4c7d56(0x150)][_0x4c7d56(0x17d)](_0x31e117),this[_0x4c7d56(0x17e)][_0x4c7d56(0x17d)](this[_0x4c7d56(0x150)]);}};myGameArea[_0x2cae4b(0x15c)](),load(),restart();
This is Obfuscated.
https://obfuscator.io/
Related
Please i need help: Trying to have my animation move from initial coordinates to new inputted coordinates using JavaScript
I have Layout with a machine, i intend to have this machine (purple animation) move from point A to point B based on input cordinate x and cordinate Y. I followed some online tutorials but still not been able to get it. The animation currently moves manually with arrow keys but i intend to have it move automatically. The aim is to have the animation move at a slow frame pace to the inserted coordinates. Any help will be appreciated. HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title> Farm Harvest </title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="grid"></div> <input type="number" id = 'cords1' placeholder="X-Cordinates"> <input type="number" id = 'cords2' placeholder="Y-Cordinates"> <button id = "mybtn" onclick="myCords();">Get Value</button> <script src="app.js"></script> </body> </html> CSS: .grid { position: absolute; width: 560px; height: 300px; border: solid 1px black; margin-top: 100px; } .user { position: absolute; width: 30px; height: 20px; background-color: blueviolet; } .block { position: absolute; width: 100px; height: 20px; background-color: blue; } JS: const grid = document.querySelector('.grid') const value1 = document.getElementById('cord1') const value2 = document.getElementById('cord2') const blockWidth = 100 const blockHeight = 20 const boardWidth = 560 const boardHeight = 300 var mouseX, mouseY; var stepWidthFactor = 200; const userStart = [10, 270] let currentPosition = userStarnst userStart1 = [10, 270] let currentPosition1 = userStart1 const user1 = [10, 270] let currentPosition2 = user1 //my block class Block { constructor(xAxis, yAxis) { this.bottomLeft = [xAxis, yAxis] this.bottomRight = [xAxis + blockWidth, yAxis] this.topRight = [xAxis + blockWidth, yAxis + blockHeight] this.topLeft = [xAxis, yAxis + blockHeight] } } class moveblock{ constructor(xAxis,yAxis){ this.xAxis = inputval0; this.yAxis = inputval1; let currentPosition3 = user2; } } //all my blocks const blocks = [ new Block(120, 210), new Block(230, 210), new Block(340, 210), new Block(120, 140), new Block(230, 140), new Block(340, 140), new Block(120, 70), new Block(230, 70), new Block(340, 70), ] //draw my blocks function addBlocks() { for (let i = 0; i < blocks.length; i++) { const block = document.createElement('div') block.classList.add('block') block.style.left = blocks[i].bottomLeft[0] + 'px' block.style.bottom = blocks[i].bottomLeft[1] + 'px' grid.appendChild(block) console.log(blocks[i].bottomLeft) } } addBlocks() //add user const user = document.createElement('div') user.classList.add('user') grid.appendChild(user) drawUser() //move user function moveUser(e) { switch (e.key) { case 'ArrowLeft': if (currentPosition[0] > 0) { currentPosition[0] -= 10 console.log(currentPosition[0] > 0) drawUser() } break case 'ArrowRight': if (currentPosition[0] < (boardWidth - blockWidth)) { currentPosition[0] += 10 console.log(currentPosition[0]) drawUser() } break case 'ArrowDown': if (currentPosition1[0] < (boardHeight - blockHeight)) { currentPosition1[0] += 10 console.log(currentPosition1[0]>0) drawUser() } break case 'ArrowUp': if (currentPosition1[0] > 0) { currentPosition1[0] -= 10 console.log(currentPosition1[0]) drawUser() } break } } document.addEventListener('keydown', moveUser) //draw User function drawUser() { user.style.top = currentPosition1 [0] + 'px' user.style.left = currentPosition[0] + 'px' user.style.bottom = currentPosition[0] + 'px' user.style.right = currentPosition[0] + 'px' } function myCords(){ const user2 = [inputval0,inputval1] let currentPosition3 = user2; var inputval0 = document.getElementById('cords1').value; var inputval1 = document.getElementById('cords2').value; if(inputval0 < boardHeight && inputval1 < boardWidth && inputval0 != 0 && inputval1 != 0){ alert("good cords " + "X: "+ inputval0 + " " +"Y: " +inputval1) } else{ alert("wrong cordinates") } }document.addEventListener('onclick',myCords) function drawnewUser(){ user.style.left = currentPosition + 'px'; user.style.top = currentPosition + 'px' user.style.bottom = currentPosition + 'px' user.style.right = currentPosition + 'px' }
How to add a game menu
I am trying to add a generic game menu with "start" to initiate the game. How do I go about doing this? Here is the code: var LEFT_KEY = 37; var UP_KEY = 38; var RIGHT_KEY = 39; var DOWN_KEY = 40; var SPACE_KEY = 32; var HERO_MOVEMENT = 3; var lastLoopRun = 0; var score = 0; var iterations = 0; var controller = new Object(); var enemies = new Array(); function createSprite(element, x, y, w, h) { var result = new Object(); result.element = element; result.x = x; result.y = y; result.w = w; result.h = h; return result; } function toggleKey(keyCode, isPressed) { if (keyCode == LEFT_KEY) { controller.left = isPressed; } if (keyCode == RIGHT_KEY) { controller.right = isPressed; } if (keyCode == UP_KEY) { controller.up = isPressed; } if (keyCode == DOWN_KEY) { controller.down = isPressed; } if (keyCode == SPACE_KEY) { controller.space = isPressed; } } function intersects(a, b) { return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y; } function ensureBounds(sprite, ignoreY) { if (sprite.x < 20) { sprite.x = 20; } if (!ignoreY && sprite.y < 20) { sprite.y = 20; } if (sprite.x + sprite.w > 480) { sprite.x = 480 - sprite.w; } if (!ignoreY && sprite.y + sprite.h > 480) { sprite.y = 480 - sprite.h; } } function setPosition(sprite) { var e = document.getElementById(sprite.element); e.style.left = sprite.x + 'px'; e.style.top = sprite.y + 'px'; } function handleControls() { if (controller.up) { hero.y -= HERO_MOVEMENT; } if (controller.down) { hero.y += HERO_MOVEMENT; } if (controller.left) { hero.x -= HERO_MOVEMENT; } if (controller.right) { hero.x += HERO_MOVEMENT; } if (controller.space) { var laser = getFireableLaser(); if (laser) { laser.x = hero.x + 9; laser.y = hero.y - laser.h; } } ensureBounds(hero); } function getFireableLaser() { var result = null; for (var i = 0; i < lasers.length; i++) { if (lasers[i].y <= -120) { result = lasers[i]; } } return result; } function getIntersectingLaser(enemy) { var result = null; for (var i = 0; i < lasers.length; i++) { if (intersects(lasers[i], enemy)) { result = lasers[i]; break; } } return result; } function checkCollisions() { for (var i = 0; i < enemies.length; i++) { var laser = getIntersectingLaser(enemies[i]); if (laser) { var element = document.getElementById(enemies[i].element); element.style.visibility = 'hidden'; element.parentNode.removeChild(element); enemies.splice(i, 1); i--; laser.y = -laser.h; score += 100; } else if (intersects(hero, enemies[i])) { gameOver(); } else if (enemies[i].y + enemies[i].h >= 500) { var element = document.getElementById(enemies[i].element); element.style.visibility = 'hidden'; element.parentNode.removeChild(element); enemies.splice(i, 1); i--; } } } function gameOver() { var element = document.getElementById(hero.element); element.style.visibility = 'hidden'; element = document.getElementById('gameover'); element.style.visibility = 'visible'; } function showSprites() { setPosition(hero); for (var i = 0; i < lasers.length; i++) { setPosition(lasers[i]); } for (var i = 0; i < enemies.length; i++) { setPosition(enemies[i]); } var scoreElement = document.getElementById('score'); scoreElement.innerHTML = 'SCORE: ' + score; } function updatePositions() { for (var i = 0; i < enemies.length; i++) { enemies[i].y += 4; enemies[i].x += getRandom(7) - 3; ensureBounds(enemies[i], true); } for (var i = 0; i < lasers.length; i++) { lasers[i].y -= 12; } } function addEnemy() { var interval = 50; if (iterations > 1500) { interval = 5; } else if (iterations > 1000) { interval = 20; } else if (iterations > 500) { interval = 35; } if (getRandom(interval) == 0) { var elementName = 'enemy' + getRandom(10000000); var enemy = createSprite(elementName, getRandom(450), -40, 35, 35); var element = document.createElement('div'); element.id = enemy.element; element.className = 'enemy'; document.children[0].appendChild(element); enemies[enemies.length] = enemy; } } function getRandom(maxSize) { return parseInt(Math.random() * maxSize); } function loop() { if (new Date().getTime() - lastLoopRun > 40) { updatePositions(); handleControls(); checkCollisions(); addEnemy(); showSprites(); lastLoopRun = new Date().getTime(); iterations++; } setTimeout('loop();', 2); } document.onkeydown = function(evt) { toggleKey(evt.keyCode, true); }; document.onkeyup = function(evt) { toggleKey(evt.keyCode, false); }; var hero = createSprite('hero', 250, 460, 20, 20); var lasers = new Array(); for (var i = 0; i < 3; i++) { lasers[i] = createSprite('laser' + i, 0, -120, 2, 50); } loop(); #hero { /* background: #ff0000; */ background-image: url("man-of-space.png"); width: 40px; height: 40px; position: absolute; } #background { background-image: url("space.png"); /* background: #000000; */ width: 500px; height: 500px; position: absolute; left: 0px; top: 0px; } .laser { background: #00ff00; width: 2px; height: 50px; position: absolute; } .enemy { background-image: url("spaceship.png"); background-size: 40px 40px; width: 40px; height: 40px; position: absolute; } #score { color: #ffffff; font-size: 18pt; position: absolute; left: 20px; top: 20px; } #gameover { color: #ff0000; font-size: 20px; position: absolute; left: 160px; top: 200px; visibility: hidden; } <div id="background"></div> <div id="hero"></div> <div class="laser" id="laser0"></div> <div class="laser" id="laser1"></div> <div class="laser" id="laser2"></div> <div id="score"></div> <div id="gameover">GAME OVER</div>
You could wrap your game UI in a <div id="game" style="display: none;"> element so it will be hidden when the page is loaded. Then wrap your start menu in a <div id="startMenu"> element with a <button id="startButton">Start</button> that will be used to hide the start menu and show the game UI. In your JS code you could wrap your game in a function so it can be started when you call it. HTML: <div id="startMenu"> <button id="startButton">Start</button> </div> <div id="game" style="display: none;"> <div id="background"></div> <div id="hero"></div> <div class="laser" id="laser0"></div> <div class="laser" id="laser1"></div> <div class="laser" id="laser2"></div> <div id="score"></div> <div id="gameover">GAME OVER</div> </div> JS: function startGame() { var LEFT_KEY = 37; var UP_KEY = 38; var RIGHT_KEY = 39; var DOWN_KEY = 40; var SPACE_KEY = 32; var HERO_MOVEMENT = 3; [...Your game code...] loop(); } document.getElementById('startButton').onclick = function() { document.getElementById('startMenu').style.display = "none"; document.getElementById('game').style.display = ""; startGame(); }; Now you have a start menu (<div id="startMenu">) that you can customize however you like, and a game UI (<div id="game">) that will be shown only after the start button is pressed.
Add more HTML would be my suggestion. Maybe make a div that has all the start screen elements you need in it. When the start function happens, set that div's innerHTML to "". Example: document.getElementById('yourDivIdHere').innerHTML = '';
How to keep an image outside of a div?
I am creating a maze, and I want the image following the mouse not able to go through the divs to get to the maze. For now, I have set up only one div, so I can get the idea of what I need to do. How can I achieve this? var startMove; $(document).mousemove(function(e) { var DIFF_SNAP = 10; var DIFF_UNSNAP = 100; var difLeft = $('#image').offset().left - e.pageX; var difTop = $('#image').offset().top - e.pageY; if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) { startMove = true; $('html').removeClass('showCursor'); } else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) { startMove = false; } if (startMove) { $("#image").css({ left: e.pageX, top: e.pageY }); } else { $('html').addClass('showCursor'); } }); $(document).mouseleave(function() { startMove = false; }) $("#drop").mouseenter(function(){ if(startMove) alert("Success"); }); html {cursor: none;} html.showCursor{cursor: default;} #image{ position:absolute; width:25px; z-index: 100; height:auto; } #drop{ width:100px; height:100px; background:aqua; position: absolute; left:200px; top: 300px; z-index:99 } .maze { width: 150px; margin-left: 500px; height:150px; background: black; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/> <div id="drop"> </div> <div class="maze"> </div> Jsfiddle: https://jsfiddle.net/3x7cgLdr/27/
I made a fiddle. The collision works. Now it's missing to count the collision sides to avoid the cursor pass the maze. var isMoving = false; var cursor = { lx: 0, ly: 0, x: 0, y: 0, width: document.getElementById("image").width, height: document.getElementById("image").height, hitting: false, sides: [] }, cursorElement; var divs, divs_L, div_i, divBd; var cur_bottom, div_bottom, cur_right, div_right; var b_collision, t_collision, l_collision, r_collision; function onCursorMove(e) { cursor.lx = cursor.x; cursor.ly = cursor.y; cursor.x = e.clientX; cursor.y = e.clientY; divs = document.getElementsByClassName("hitme"); divs_L = divs.length; for (div_i = 0; div_i < divs_L; div_i++) { divBd = divs[div_i].getBoundingClientRect(); if (cursor.x < divBd.left + divBd.width && cursor.x + cursor.width > divBd.left && cursor.y < divBd.top + divBd.height && cursor.y + cursor.height > divBd.top) { hitting = true; cur_bottom = cursor.y + cursor.height; div_bottom = divBd.top + divBd.height; cur_right = cursor.x + cursor.width; div_right = divBd.left + divBd.width; b_collision = div_bottom - cursor.y; t_collision = cur_bottom - divBd.y; l_collision = cur_right - divBd.x; r_collision = div_right - cursor.x; if (t_collision < b_collision && t_collision < l_collision && t_collision < r_collision) { //Top collision cursor.y = divBd.top - cursor.height; } else if (b_collision < t_collision && b_collision < l_collision && b_collision < r_collision) { cursor.y = divBd.bottom; //bottom collision } if (l_collision < r_collision && l_collision < t_collision && l_collision < b_collision) { //Left collision cursor.x = divBd.left - cursor.width; } else if (r_collision < l_collision && r_collision < t_collision && r_collision < b_collision) { //Right collision cursor.x = divBd.right; } break } } cursorElement = document.getElementById("image"); cursorElement.style.left = cursor.x + "px"; cursorElement.style.top = cursor.y + "px"; } window.onmousemove = onCursorMove;
How can i implement a simple menu for my game made with HTML?
i'm making a simple game with HTML only, more or less it works... My question is if i can make a simple menu /with "click to start" or something similar/ with an image at the background and 1 button to start the game. And if i can make it in the same archive. Thanks. <canvas id="ctx" width="1024" height="800" style="border:3px solid #000000;"></canvas> <script> var Height = 800; var Width = 1024; var timeElapset = Date.now(); var ctx = document.getElementById("ctx").getContext("2d"); ctx.font = '30px Consolas'; var frameCount = 0; var score = 0; var player = { x:50, spdX:30, y:40, spdY:30, name:'P', hp:10, width:20, height:20, color:'green', }; var enemyList = {}; getDistance = function (Obj1,Obj2){ var vx = Obj1.x - Obj2.x; var vy = Obj1.y - Obj2.y; return Math.sqrt((vx*vx)+(vy*vy)); } checkCollision = function (Obj1,Obj2){ var rect1 = { x: Obj1.x - Obj1.width/2, y: Obj1.y - Obj1.height/2, height: Obj1.height, width: Obj1.width, } var rect2 = { x: Obj2.x - Obj2.width/2, y: Obj2.y - Obj2.height/2, height: Obj2.height, width: Obj2.width, } return testCollisionRectRect(rect1,rect2); //true o false } Enemy = function (id,x,y,spdX,spdY,width,height){ var enemy = { x:x, spdX:spdX, y:y, spdY:spdY, name:'E', id:id, width:width, height:height, color:'black', }; enemyList[id] = enemy; } document.onmousemove = function(mouse){ var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left; var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top; if(mouseX < player.width/2) mouseX = player.width/2; if(mouseX > Width-player.width/2) mouseX = Width - player.width/2; if(mouseY < player.height/2) mouseY = player.height/2; if(mouseY > Height - player.height/2) mouseY = Height - player.height/2; player.x = mouseX; player.y = mouseY; } updateEntity = function (Z){ updatePosition(Z); drawPlayer(Z); } updatePosition = function(Z){ Z.x += Z.spdX; Z.y += Z.spdY; if(Z.x < 0 || Z.x > Width){ Z.spdX = -Z.spdX; } if(Z.y < 0 || Z.y > Height){ Z.spdY = -Z.spdY; } } testCollisionRectRect = function(rect1,rect2){ return rect1.x <= rect2.x+rect2.width && rect2.x <= rect1.x+rect1.width && rect1.y <= rect2.y + rect2.height && rect2.y <= rect1.y + rect1.height; } drawPlayer = function(Z){ ctx.save(); ctx.fillStyle = Z.color; ctx.fillRect(Z.x-Z.width/2,Z.y-Z.height/2,Z.width,Z.height); ctx.restore(); } update = function(){ ctx.clearRect(0,0,Width,Height); frameCount++; score++; if(frameCount % 100 == 0) randomGenerateEnemy(); for(var key in enemyList){ updateEntity(enemyList[key]); var isColliding = checkCollision(player, enemyList[key]); if(isColliding){ player.hp = player.hp -1; } } if(player.hp <= 0){ var timeSurvived = Date.now() - timeElapset; console.log("Has ganado Kappa, Tiempo vivo " + timeSurvived + " ms."); ctx.fillText(" You Lose! ", Width/2, Height/2); GameEngine(); } drawPlayer(player); ctx.fillText(player.hp + " Hp",20,30); ctx.fillText('Puntuacion: ' + score/10,700,30); } GameEngine = function(){ player.hp = 13; timeElapset = Date.now(); frameCount = 0; score = 0; enemyList = {}; randomGenerateEnemy(); randomGenerateEnemy(); randomGenerateEnemy(); randomGenerateEnemy(); } randomGenerateEnemy = function(){ var x = Math.random()*Width; var y = Math.random()*Height; var height = 10 + Math.random()*70; var width = 10 + Math.random()*70; var id = Math.random(); var spdX = 5 + Math.random() * 5; var spdY = 5 + Math.random() * 5; Enemy(id,x,y,spdX,spdY,width,height); } GameEngine(); setInterval(update,30); </script> That's what i have.
The code also contains javascript.For proper gaming function .js file has to be called on your html page.Also use css to make it attractive.Consider this example enter code here <html> <head> <title>Your game title</title> <script type="text/javascript" src="src/Common.js"></script> <script type="text/javascript" src="src/Perlin.js"></script> <script type="text/javascript" src="src/ChaikinCurve.js"></script> <script type="text/javascript"> var app = null; window.onload = function() { utils.loadShaderXml("src/render/shaders.xml", null, function(shaders) { if (shaders instanceof Exception) { app = shaders; } else { try { app = new App('canvas', shaders, null); } catch (e) { app = e; } } }); document.onselectstart = function () { return false; }; }; function application() { if (app == null) { alert("Application is absent"); throw "no application"; } else if (app instanceof Exception) { alert("An exception occured while creating the application:\n" + app.message); throw app; } else { return app; } } </script> <style type="text/css"> body{ margin: 0px; padding: 0px; overflow: hidden; background: #000; } #canvas-holder.active { position: absolute; padding: 0px; left: 50%; top: 50%; } #canvas-holder.inactive { position: absolute; top:50%; width: 100%; text-align: center; } #canvas { padding: 0px; width: 100%; height: 100%; color: #fff; font-family: Allan, Arial; font-size: 40px; } </style> </head> <body> <div id="canvas-holder" class="inactive"> <div id="canvas">Your game` is loading...</div> </div> <div style="font-family: Lobster; visibility: hidden">one</div> <div style="font-family: Allan; visibility: hidden">two</div> <div style="font-family: Meddon; visibility: hidden">three</div> <div style="font-family: Cuprum; visibility: hidden">four</div> </body> </html>
How can I fix height, container with scrollbar
I'm using a simple JavaScript. I change the container's height and width. I think I need to fix the JavaScript, because it is working on the container which as height set in px, but I have set the height as %. The problem is appearing when you resize (you can't see full img or there is too much space) on bottom of the container. Or maybe I'm wrong... Any tips? function jsScroller (o, w, h) { var self = this; var list = o.getElementsByTagName("div"); for (var i = 0; i < list.length; i++) { if (list[i].className.indexOf("Scroller-Container") > -1) { o = list[i]; } } //Private methods this._setPos = function (x, y) { if (x < this.viewableWidth - this.totalWidth) x = this.viewableWidth - this.totalWidth; if (x > 0) x = 0; if (y < this.viewableHeight - this.totalHeight) y = this.viewableHeight - this.totalHeight; if (y > 0) y = 0; this._x = x; this._y = y; with (o.style) { left = this._x +"px"; top = this._y +"px"; } }; //Public Methods this.reset = function () { this.content = o; this.totalHeight = o.offsetHeight; this.totalWidth = o.offsetWidth; this._x = 0; this._y = 0; with (o.style) { left = "0px"; top = "0px"; } }; this.scrollBy = function (x, y) { this._setPos(this._x + x, this._y + y); }; this.scrollTo = function (x, y) { this._setPos(-x, -y); }; this.stopScroll = function () { if (this.scrollTimer) window.clearInterval(this.scrollTimer); }; this.startScroll = function (x, y) { this.stopScroll(); this.scrollTimer = window.setInterval( function(){ self.scrollBy(x, y); }, 40 ); }; this.swapContent = function (c, w, h) { o = c; var list = o.getElementsByTagName("div"); for (var i = 0; i < list.length; i++) { if (list[i].className.indexOf("Scroller-Container") > -1) { o = list[i]; } } if (w) this.viewableWidth = w; if (h) this.viewableHeight = h; this.reset(); }; //variables this.content = o; this.viewableWidth = w; this.viewableHeight = h; this.totalWidth = o.offsetWidth; this.totalHeight = o.offsetHeight; this.scrollTimer = null; this.reset(); }; function jsScrollbar (o, s, a, ev) { var self = this; this.reset = function () { //Arguments that were passed this._parent = o; this._src = s; this.auto = a ? a : false; this.eventHandler = ev ? ev : function () {}; //Component Objects this._up = this._findComponent("Scrollbar-Up", this._parent); this._down = this._findComponent("Scrollbar-Down", this._parent); this._yTrack = this._findComponent("Scrollbar-Track", this._parent); this._yHandle = this._findComponent("Scrollbar-Handle", this._yTrack); //Height and position properties this._trackTop = findOffsetTop(this._yTrack); this._trackHeight = this._yTrack.offsetHeight; this._handleHeight = this._yHandle.offsetHeight; this._x = 0; this._y = 0; //Misc. variables this._scrollDist = 5; this._scrollTimer = null; this._selectFunc = null; this._grabPoint = null; this._tempTarget = null; this._tempDistX = 0; this._tempDistY = 0; this._disabled = false; this._ratio = (this._src.totalHeight - this._src.viewableHeight)/(this._trackHeight - this._handleHeight); this._yHandle.ondragstart = function () {return false;}; this._yHandle.onmousedown = function () {return false;}; this._addEvent(this._src.content, "mousewheel", this._scrollbarWheel); this._removeEvent(this._parent, "mousedown", this._scrollbarClick); this._addEvent(this._parent, "mousedown", this._scrollbarClick); this._src.reset(); with (this._yHandle.style) { top = "0px"; left = "0px"; } this._moveContent(); if (this._src.totalHeight < this._src.viewableHeight) { this._disabled = true; this._yHandle.style.visibility = "hidden"; if (this.auto) this._parent.style.visibility = "hidden"; } else { this._disabled = false; this._yHandle.style.visibility = "visible"; this._parent.style.visibility = "visible"; } }; this._addEvent = function (o, t, f) { if (o.addEventListener) o.addEventListener(t, f, false); else if (o.attachEvent) o.attachEvent('on'+ t, f); else o['on'+ t] = f; }; this._removeEvent = function (o, t, f) { if (o.removeEventListener) o.removeEventListener(t, f, false); else if (o.detachEvent) o.detachEvent('on'+ t, f); else o['on'+ t] = null; }; this._findComponent = function (c, o) { var kids = o.childNodes; for (var i = 0; i < kids.length; i++) { if (kids[i].className && kids[i].className == c) { return kids[i]; } } }; //Thank you, Quirksmode function findOffsetTop (o) { var t = 0; if (o.offsetParent) { while (o.offsetParent) { t += o.offsetTop; o = o.offsetParent; } } return t; }; this._scrollbarClick = function (e) { if (self._disabled) return false; e = e ? e : event; if (!e.target) e.target = e.srcElement; if (e.target.className.indexOf("Scrollbar-Up") > -1) self._scrollUp(e); else if (e.target.className.indexOf("Scrollbar-Down") > -1) self._scrollDown(e); else if (e.target.className.indexOf("Scrollbar-Track") > -1) self._scrollTrack(e); else if (e.target.className.indexOf("Scrollbar-Handle") > -1) self._scrollHandle(e); self._tempTarget = e.target; self._selectFunc = document.onselectstart; document.onselectstart = function () {return false;}; self.eventHandler(e.target, "mousedown"); self._addEvent(document, "mouseup", self._stopScroll, false); return false; }; this._scrollbarDrag = function (e) { e = e ? e : event; var t = parseInt(self._yHandle.style.top); var v = e.clientY + document.body.scrollTop - self._trackTop; with (self._yHandle.style) { if (v >= self._trackHeight - self._handleHeight + self._grabPoint) top = self._trackHeight - self._handleHeight +"px"; else if (v <= self._grabPoint) top = "0px"; else top = v - self._grabPoint +"px"; self._y = parseInt(top); } self._moveContent(); }; this._scrollbarWheel = function (e) { e = e ? e : event; var dir = 0; if (e.wheelDelta >= 120) dir = -1; if (e.wheelDelta <= -120) dir = 1; self.scrollBy(0, dir * 20); e.returnValue = false; }; this._startScroll = function (x, y) { this._tempDistX = x; this._tempDistY = y; this._scrollTimer = window.setInterval(function () { self.scrollBy(self._tempDistX, self._tempDistY); }, 40); }; this._stopScroll = function () { self._removeEvent(document, "mousemove", self._scrollbarDrag, false); self._removeEvent(document, "mouseup", self._stopScroll, false); if (self._selectFunc) document.onselectstart = self._selectFunc; else document.onselectstart = function () { return true; }; if (self._scrollTimer) window.clearInterval(self._scrollTimer); self.eventHandler (self._tempTarget, "mouseup"); }; this._scrollUp = function (e) {this._startScroll(0, -this._scrollDist);}; this._scrollDown = function (e) {this._startScroll(0, this._scrollDist);}; this._scrollTrack = function (e) { var curY = e.clientY + document.body.scrollTop; this._scroll(0, curY - this._trackTop - this._handleHeight/2); }; this._scrollHandle = function (e) { var curY = e.clientY + document.body.scrollTop; this._grabPoint = curY - findOffsetTop(this._yHandle); this._addEvent(document, "mousemove", this._scrollbarDrag, false); }; this._scroll = function (x, y) { if (y > this._trackHeight - this._handleHeight) y = this._trackHeight - this._handleHeight; if (y < 0) y = 0; this._yHandle.style.top = y +"px"; this._y = y; this._moveContent(); }; this._moveContent = function () { this._src.scrollTo(0, Math.round(this._y * this._ratio)); }; this.scrollBy = function (x, y) { this._scroll(0, (-this._src._y + y)/this._ratio); }; this.scrollTo = function (x, y) { this._scroll(0, y/this._ratio); }; this.swapContent = function (o, w, h) { this._removeEvent(this._src.content, "mousewheel", this._scrollbarWheel, false); this._src.swapContent(o, w, h); this.reset(); }; this.reset(); }; #no-template-pager { width: 34%; height: 25vw; overflow: hidden; white-space: nowrap; float: left; } .Scroller-Container { position: relative; width: 100%; height: 100%; } #Scrollbar-Container { position: relative; top: 0px; left: 0%; background: green; width: 1%; height: 100%; overflow: hidden; } .Scrollbar-Track { width: 100%; height: 100%; position: absolute; background: #222; } .Scrollbar-Handle { position: absolute; width: 100%; height: 70%; background: #8E8E8E; -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; } .Scrollbar-Handle:hover, .Scrollbar-Handle:active { background: #fff; } #slider2 { margin: 50px auto; width: 60%; height: 25vw; background: #222; } #youtube { width: 65%; height: 25vw; float: right; background: blue; } .thumbs { width: 100%; height: 25%; box-shadow: 0 -1px 0 #5A5A5A, 0 -1px 0 #707070; } .thumbs img { margin: 3% 4%; width: 80%; height: 80%; float: left; } <section id="slider2"> <div id="youtube"> </div> <div id="no-template-pager" class="cycle-pager external"> <div class="Scroller-Container"> <!-- using thumbnail image files would be even better! --> <div class="thumbs"> <img src="http://img.youtube.com/vi/Je7VuV9yHIw/mqdefault.jpg"> </div> <div class="thumbs"> <img src="http://img.youtube.com/vi/uxps_fYUeJk/mqdefault.jpg"> </div> <div class="thumbs"> <img src="http://img.youtube.com/vi/Zvr3cwbbqHU/mqdefault.jpg"> </div> <div class="thumbs"> <img src="http://img.youtube.com/vi/Ka9xtXPD3BA/mqdefault.jpg"> </div> <div class="thumbs"> <img src="http://img.youtube.com/vi/U8HVQXkeU8U/mqdefault.jpg"> </div> <div class="thumbs"> <img src="http://img.youtube.com/vi/e7_UUfokexM/mqdefault.jpg"> </div> </div> </div> <div id="Scrollbar-Container"> <div class="Scrollbar-Track"> <div class="Scrollbar-Handle"></div> </div> </div> </section> <script> var scroller = null; var scrollbar = null; window.onload = function () { scroller = new jsScroller(document.getElementById("no-template-pager"), 400, 200); scrollbar = new jsScrollbar (document.getElementById("Scrollbar-Container"), scroller, true); } </script> Link to CodePen 1. and to Javascript 2.: [1]: http://codepen.io/psairidas/pen/RaVwzw [2]: http://www.n-son.com/scripts/jsScrolling/jsScrollbar.html
You should probably set a max-height or max-width in pixels, so that it will resize but once it hits that max-height or max-width it won't get any smaller. Then if you want it to scroll, you can set overflow: scroll or overflow: auto (auto is generally recommended).