I have a few problem with html5. I created a new webpage and add canvas at the middle of that page.Then created new js file that have a script for canvas and import it to webpage but webpage's canvas still nothing happen.
This is my code. index.html in root folder, style.css in css/ , script.js in js/
function startnewgame(){
score =0;
player.hp =10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount =0;
enemylist ={} ;
bulletlist ={};
upgradelist ={};
randomspwanenemy();
}
function update(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Score = "+score,200,30);
score ++;
frameCount++;
if(frameCount % 100 === 0)random
spwanenemy();
if(frameCount % 75 === 0)randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for(var i in bulletlist){
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false ;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i],enemylist[j]);
if(cod){
toRemove = true;
delete enemylist[j];
score+=1000;
break;
}
}
if(toRemove)delete bulletlist[i];
}
for(var i in upgradelist){
updateplayer(upgradelist[i]);
var temp = getdistant(player,upgradelist[i]);
if(temp){
if(upgradelist[i].type === 'score'){
score += 100;
}
if(upgradelist[i].type ==='atkspd'){
player.atkspd +=5;
}
delete upgradelist[i];
}
}
for(var i in enemylist){
updateplayer(enemylist[i]);
var temp = getdistant(player,enemylist[i]);
death(temp);
}
}
function drawplayer(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
ctx.fillText("HP = "+player.hp,20,30);
ctx.fillText("bullet = "+player.attackcounter,20,80);
}
function drawenemy(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
}
function updateplayer(x){
if(x.x+x.width/2>=WIDTH){
x.x=WIDTH-x.width/2;
x.spdX=-x.spdX;
}
if(x.x-x.width/2<=0){
x.x = x.width/2;
x.spdX=-x.spdX;
}
if(x.y+x.height/2>=HEIGHT){
x.y = HEIGHT-x.height/2;
x.spdY=-x.spdY;
}
if(x.y-x.height/2<=0){
x.y = x.height/2;
x.spdY=-x.spdY;
}
x.x+=x.spdX;
x.y+=x.spdY;
drawenemy(x);
}
function adde(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'red'
};
enemylist[id]= earth;
}
function addupgrade(id,x,y,spdX,spdY,width,height,color,type){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : color,
type : type
};
upgradelist[id]= earth;
}
function addbullet(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'black',
timer: 0
};
bulletlist[id]= earth;
}
function getdistant(earth1,earth2){
var rect1 ={
x:earth1.x-earth1.width/2,
y:earth1.y-earth1.height/2,
width:earth1.width,
height:earth1.height
};
var rect2 ={
x:earth2.x-earth2.width/2,
y:earth2.y-earth2.height/2,
width:earth2.width,
height:earth2.height
};
return testcol(rect1,rect2);
}
function death(x){
if(x){
player.hp -= 1;
if(player.hp == 0){
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score "+ score );
startnewgame();
}
}
}
function randomspwanenemy(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 +Math.random()*30;
var width= 10 + Math.random()*30;
var spdY = Math.random()*5 +5;
var spdX = Math.random()*5 +5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id,x,y,spdX,spdY,width,height);
}
function randomspwanupgrade(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 ;
var width= 10 ;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if(sample >0.5){
var type = 'score';
var color ='lightblue';
}
else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id,x,y,spdX,spdY,width,height,color,type);
}
function randomspwanbullet(earth,overangle){
var x = player.x;
var y = player.y;
var height = 10 ;
var width= 10 ;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle)*10 );
var spdX = (Math.cos(angle)*10 );
var id = Math.random();
addbullet(id,x,y,spdX,spdY,width,height);
}
function testcol(earth1,earth2){
var lasthit = Date.now()-timewhenlasthit;
if( earth1.x <= earth2.x+earth2.width
&& earth2.x <= earth1.x+earth1.width
&& earth1.y <= earth2.y+earth2.height
&& earth2.y <= earth1.y+earth1.height
&& lasthit >= 1000)
{
timewhenlasthit=Date.now();
return 1;
}
}
function pp(x){
if(x>0.5)return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount =0;
ctx.font = '30 px Arial';
var score =0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse){
var mouseX = mouse.clientX- document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY-document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY,mouseX) ;
/* 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;*/
}
document.onclick = function(mouse){
if (player.attackcounter > 25) {
randomspwanbullet(player,player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse){
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player,i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event){
if (event.keyCode===68) {
player.pressingRight = true;
}
else if (event.keyCode===83) {
player.pressingDown = true ;
}
else if (event.keyCode===65) {
player.pressingLeft = true ;
}
else if (event.keyCode===87) {
player.pressingUp = true ;
}
}
document.onkeyup = function(event){
if (event.keyCode===68) {
player.pressingRight = false;
}
else if (event.keyCode===83) {
player.pressingDown = false ;
}
else if (event.keyCode===65) {
player.pressingLeft = false ;
}
else if (event.keyCode===87) {
player.pressingUp = false ;
}
}
function updateplayerposition() {
if(player.pressingRight)player.x+=10
if(player.pressingLeft)player.x-=10
if(player.pressingUp)player.y-=10
if(player.pressingDown)player.y+=10
if(player.x <player.width/2)player.x=player.width/2;
if(player.x>WIDTH-player.width/2)player.x = WIDTH-player.width/2;
if(player.y<player.height/2)player.y=player.height/2;
if(player.y>HEIGHT-player.height/2)player.y = HEIGHT-player.height/2;
}
var player = {
name :'E' ,
x : 40 ,
spdX : 30 ,
y : 40 ,
spdY : 5 ,
hp : 10 ,
width : 20 ,
height : 20,
atkspd : 1,
color : 'green',
attackcounter : 0,
pressingDown : false,
pressingUp : false,
pressingLeft : false,
pressingRight : false,
aimAngle : 0
};
var enemylist ={};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update,40);
}
#header{
background: #202020 ;
font-size: 36px;
text-align: center;
padding:0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx{
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu{
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2{
text-align: center;
font-size: 30px;
}
nav#leftmenu ul{
list-style: none;
padding: 0;
}
nav#leftmenu li{
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a{
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id ="ctx" width ="800" height="600" style = "border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game</li>
<li>Pause Game</li>
<li>Option</li>
<li>End it now</li>
</ul>
</nav>
</section>
</body>
</html>
Ps. this ti my first post,Sorry if I did something wrong.
Edit: canvas id from canvas to ctx
Here's a snippet that's working and drawing correctly. It was just a little typo in the update function, writing it like:
if (frameCount % 100 === 0) random
spwanenemy();
instead of:
if (frameCount % 100 === 0) randomspwanenemy();
So, yea, just a little typo! Understanding errors from the developer console (F12) and spotting what's wrong is a vital skill. Keep practicing!
function startnewgame() {
score = 0;
player.hp = 10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount = 0;
enemylist = {};
bulletlist = {};
upgradelist = {};
randomspwanenemy();
}
function update() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.fillText("Score = " + score, 200, 30);
score++;
frameCount++;
if (frameCount % 100 === 0) randomspwanenemy();
if (frameCount % 75 === 0) randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for (var i in bulletlist) {
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i], enemylist[j]);
if (cod) {
toRemove = true;
delete enemylist[j];
score += 1000;
break;
}
}
if (toRemove) delete bulletlist[i];
}
for (var i in upgradelist) {
updateplayer(upgradelist[i]);
var temp = getdistant(player, upgradelist[i]);
if (temp) {
if (upgradelist[i].type === 'score') {
score += 100;
}
if (upgradelist[i].type === 'atkspd') {
player.atkspd += 5;
}
delete upgradelist[i];
}
}
for (var i in enemylist) {
updateplayer(enemylist[i]);
var temp = getdistant(player, enemylist[i]);
death(temp);
}
}
function drawplayer(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
ctx.fillText("HP = " + player.hp, 20, 30);
ctx.fillText("bullet = " + player.attackcounter, 20, 80);
}
function drawenemy(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
}
function updateplayer(x) {
if (x.x + x.width / 2 >= WIDTH) {
x.x = WIDTH - x.width / 2;
x.spdX = -x.spdX;
}
if (x.x - x.width / 2 <= 0) {
x.x = x.width / 2;
x.spdX = -x.spdX;
}
if (x.y + x.height / 2 >= HEIGHT) {
x.y = HEIGHT - x.height / 2;
x.spdY = -x.spdY;
}
if (x.y - x.height / 2 <= 0) {
x.y = x.height / 2;
x.spdY = -x.spdY;
}
x.x += x.spdX;
x.y += x.spdY;
drawenemy(x);
}
function adde(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'red'
};
enemylist[id] = earth;
}
function addupgrade(id, x, y, spdX, spdY, width, height, color, type) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: color,
type: type
};
upgradelist[id] = earth;
}
function addbullet(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'black',
timer: 0
};
bulletlist[id] = earth;
}
function getdistant(earth1, earth2) {
var rect1 = {
x: earth1.x - earth1.width / 2,
y: earth1.y - earth1.height / 2,
width: earth1.width,
height: earth1.height
};
var rect2 = {
x: earth2.x - earth2.width / 2,
y: earth2.y - earth2.height / 2,
width: earth2.width,
height: earth2.height
};
return testcol(rect1, rect2);
}
function death(x) {
if (x) {
player.hp -= 1;
if (player.hp == 0) {
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score " + score);
startnewgame();
}
}
}
function randomspwanenemy() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10 + Math.random() * 30;
var width = 10 + Math.random() * 30;
var spdY = Math.random() * 5 + 5;
var spdX = Math.random() * 5 + 5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id, x, y, spdX, spdY, width, height);
}
function randomspwanupgrade() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10;
var width = 10;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if (sample > 0.5) {
var type = 'score';
var color = 'lightblue';
} else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id, x, y, spdX, spdY, width, height, color, type);
}
function randomspwanbullet(earth, overangle) {
var x = player.x;
var y = player.y;
var height = 10;
var width = 10;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle) * 10);
var spdX = (Math.cos(angle) * 10);
var id = Math.random();
addbullet(id, x, y, spdX, spdY, width, height);
}
function testcol(earth1, earth2) {
var lasthit = Date.now() - timewhenlasthit;
if (earth1.x <= earth2.x + earth2.width && earth2.x <= earth1.x + earth1.width && earth1.y <= earth2.y + earth2.height && earth2.y <= earth1.y + earth1.height && lasthit >= 1000) {
timewhenlasthit = Date.now();
return 1;
}
}
function pp(x) {
if (x > 0.5) return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount = 0;
ctx.font = '30 px Arial';
var score = 0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse) {
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY, mouseX);
/* 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;*/
}
document.onclick = function(mouse) {
if (player.attackcounter > 25) {
randomspwanbullet(player, player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse) {
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player, i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event) {
if (event.keyCode === 68) {
player.pressingRight = true;
} else if (event.keyCode === 83) {
player.pressingDown = true;
} else if (event.keyCode === 65) {
player.pressingLeft = true;
} else if (event.keyCode === 87) {
player.pressingUp = true;
}
}
document.onkeyup = function(event) {
if (event.keyCode === 68) {
player.pressingRight = false;
} else if (event.keyCode === 83) {
player.pressingDown = false;
} else if (event.keyCode === 65) {
player.pressingLeft = false;
} else if (event.keyCode === 87) {
player.pressingUp = false;
}
}
function updateplayerposition() {
if (player.pressingRight) player.x += 10
if (player.pressingLeft) player.x -= 10
if (player.pressingUp) player.y -= 10
if (player.pressingDown) player.y += 10
if (player.x < player.width / 2) player.x = player.width / 2;
if (player.x > WIDTH - player.width / 2) player.x = WIDTH - player.width / 2;
if (player.y < player.height / 2) player.y = player.height / 2;
if (player.y > HEIGHT - player.height / 2) player.y = HEIGHT - player.height / 2;
}
var player = {
name: 'E',
x: 40,
spdX: 30,
y: 40,
spdY: 5,
hp: 10,
width: 20,
height: 20,
atkspd: 1,
color: 'green',
attackcounter: 0,
pressingDown: false,
pressingUp: false,
pressingLeft: false,
pressingRight: false,
aimAngle: 0
};
var enemylist = {};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update, 40);
}
#header {
background: #202020;
font-size: 36px;
text-align: center;
padding: 0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx {
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu {
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2 {
text-align: center;
font-size: 30px;
}
nav#leftmenu ul {
list-style: none;
padding: 0;
}
nav#leftmenu li {
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a {
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id="ctx" width="800" height="600" style="border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game
</li>
<li>Pause Game
</li>
<li>Option
</li>
<li>End it now
</li>
</ul>
</nav>
</section>
</body>
</html>
Related
Here is all the code for the website, it has many bugs, like the footer which is stuck in the middle. So the idea is to create 11 different tissues in the format of this image mapped to the JS I have, bit i dont know how to do that.[![sample tissue][1]][1]
I would like to create a slider that functions when you click on the collection number it switchees to the next collection.
Also all the links only take the size and not the column width when hovered.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$</title>
<link rel="stylesheet" href="normalize.css">
<style type="text/css">
* {
margin: 0;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
font-family: sans-serif;
}
body {
}
#c {
display: block;
margin: 20px auto 0;
}
#info {
position: absolute;
left: -1px;
top: -1px;
width: auto;
max-width: 420px;
height: auto;
background: #f8f8f8;
border-bottom-right-radius: 10px;
border:1px solid #ccc;
}
#top {
background: #fff;
width: 100%;
height: auto;
position: relative;
border-bottom: 1px solid #eee;
}
p {
font-family: Arial, sans-serif;
color: #666;
text-align: justify;
font-size: 16px;
margin: 0px 16px;
}
#github, #twitter {
color:#3377ee;
font-family: Helvetica, Arial, sans-serif;
font-size: 14px;
margin: 0 auto;
text-align: center;
text-decoration:none;
}
.center {
text-align: center;
}
#net {
text-align:center;
white-space:nowrap;
font-size:19px;
background:rgba(0,0,0,0.1);
padding:8px 12px;
border-radius:8px;
display:block;
color:#888;
}
#net > span {
color:#3377ee;
font-family: Helvetica, Arial, sans-serif;
font-size: 14px;
display: block;
margin: 0 auto;
text-align: center;
text-decoration:none;
}
.bull {
opacity: 0.3;
margin: 0 6px;
font-size: 14px;
}
.row {
display: flex;
flex-direction: row;
flex-wrap: wrap;
border-bottom: 1px solid black;
}
.column {
flex-basis: 100%;
border-right: 1px solid black;
}
#media screen and (min-width: 800px) {
.column {
flex: 1;
}
}
#media screen and (min-width: 800px) {
._25 {
flex: 2.5;
}
._55 {
flex: 5.5;
}
._20 {
flex: 2;
}
}
a:link {
text-decoration: none;
}
a:visited {
text-decoration: none;
color: black;
}
a:hover {
text-decoration: none;
color: white;
background: black;}
a:active {
text-decoration: none;
color: white;
background: black;
}
</style>
</head>
<body>
<div class="row">
<div class="column">
Rakṣas Sari collection
</div>
<div class="column">
Concept
</div>
<div class="column">
Process
</div>
</div>
<div class="row">
<div class="column">
Red Collection N°1
</div>
<div class="column">
Collection N°2
</div>
<div class="column">
Collection N°3
</div>
<div class="column">
Collection N°4
</div>
<div class="column">
Collection N°5
</div>
<div class="column">
Collection N°6
</div>
<div class="column">
Collection N°7
</div>
<div class="column">
Collection N°8
</div>
<div class="column">
Collection N°9
</div>
<div class="column">
Collection N°10
</div>
<div class="column">
Collection N°11
</div>
</div>
<div class="row">
<div class="column _25">
Project photoshoot
</div>
<div class="column _55">
<canvas id="c"></canvas>
<div id="top">
<a id="close" href="">Reset tissue</a>
</div>
</div>
<div class="column _20">
Red is a celebratory color. It commemorates a couple’s union. It symbolizes love, sensuality, and passion. That’s why it features prominently in auspicious occasions, such as weddings, festivals, and births. As red also signifies chastity, it is the color of choice for brides.
</div>
</div>
<footer>
<div class="row">
<div class="column">
©Copyright Angelo Barbattini
</div>
<div class="column">
ECAL 2022
</div>
</div>
</footer style="position: fixed;bottom: 0;">
<!--div id="new">
Wobble some <a target="_blank" href="https://codepen.io/dissimulate/details/dJgMaO">jelly</a> <span class="bull">•</span>
Check out my <a target="_blank" href="https://www.instagram.com/abro_oks/">instagram!</a>
</div-->
<script type="text/javascript">
document.getElementById("close").onmousedown = function (e) {
e.preventDefault();
document.getElementById("info").style.display = "none";
return false;
};
// settings
var physics_accuracy = 3,
mouse_influence = 20,
mouse_cut = 5,
gravity = 1200,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
var Point = function (x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
};
Point.prototype.update = function (delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + (this.x - this.px) * 0.99 + (this.vx / 2) * delta;
ny = this.y + (this.y - this.py) * 0.99 + (this.vy / 2) * delta;
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0;
};
Point.prototype.draw = function () {
if (!this.constraints.length) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function () {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx
? (this.x = 2 * boundsx - this.x)
: 1 > this.x && (this.x = 2 - this.x);
this.y < 1
? (this.y = 2 - this.y)
: this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function (point) {
this.constraints.push(new Constraint(this, point));
};
Point.prototype.remove_constraint = function (constraint) {
this.constraints.splice(this.constraints.indexOf(constraint), 1);
};
Point.prototype.add_force = function (x, y) {
this.vx += x;
this.vy += y;
var round = 400;
this.vx = ~~(this.vx * round) / round;
this.vy = ~~(this.vy * round) / round;
};
Point.prototype.pin = function (pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function (p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function () {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
Constraint.prototype.draw = function () {
ctx.moveTo(this.p1.x, this.p1.y);
ctx.lineTo(this.p2.x, this.p2.y);
};
var Cloth = function () {
this.points = [];
var start_x = canvas.width / 2 - (cloth_width * spacing) / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)]);
this.points.push(p);
}
}
};
Cloth.prototype.update = function () {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(0.016);
};
Cloth.prototype.draw = function () {
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
function start() {
canvas.onmousedown = function (e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
(mouse.x = e.clientX - rect.left),
(mouse.y = e.clientY - rect.top),
(mouse.down = true);
e.preventDefault();
};
canvas.onmouseup = function (e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function (e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
(mouse.x = e.clientX - rect.left),
(mouse.y = e.clientY - rect.top),
e.preventDefault();
};
canvas.oncontextmenu = function (e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = "#888";
cloth = new Cloth();
update();
}
window.onload = function () {
canvas = document.getElementById("c");
ctx = canvas.getContext("2d");
canvas.width = 560;
canvas.height = 350;
start();
};
</script>
</body>
</html>```
[1]: https://i.stack.imgur.com/Celmj.jpg
The questioner is focusing on the problem of getting an actual image to look like material being moved with the wind.
The code presented to do this divides a canvas into small rectangular elements and moves each of those as required by the 'physics' given (value of gravity/wind for example).
The original just draws grid lines for each of these areas. What we need is for the equivalent rectangle in the original image to be copied to that point.
This snippet achieves this by adding a origx/y to the info kept about each point so that we know where to find the original rectangle.
It brings the image into an img element (it is important to wait until this is loaded before doing more with it) then copies it to an off-screen canvas that has the same dimensions as the one which will hold the material. This canvas is inspected when we need the 'mini image' to put at a given point.
WARNING: this code (even without the introduction of an image) is pretty processor intensive. On a farily powerful laptop with good GPU it was taking around 19% of CPU and not much less of GPU and the fan was whirring. This is even when there is no movement of the mouse. The code could do with a thorough look through, for example to stop the timer when user activity is completed, and perhaps putting the frame rate down (it's 60fps in the given code). I would not recommend it be put in a webpage and left there running - it will be a battery drainer.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
-->
<script type="text/javascript" src=""></script>
<link rel="stylesheet" type="text/css" href="">
<style type="text/css">
body {}
.wrapper {}
* {
margin: 0;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
body {
background: #333;
}
canvas {
background: #333;
width: 100%;
height: 376px;
margin: 0 auto;
display: block;
border: solid red 2px;
}
#info {
position: absolute;
left: -1px;
top: -1px;
width: auto;
max-width: 380px;
height: auto;
background: #f2f2f2;
border-bottom-right-radius: 10px;
}
#top {
background: #fff;
width: 100%;
height: auto;
position: relative;
border-bottom: 1px solid #eee;
}
p {
font-family: Arial, sans-serif;
color: #666;
text-align: justify;
font-size: 16px;
margin: 10px;
}
a {
font-family: sans-serif;
color: #444;
text-decoration: none;
font-size: 20px;
}
#site {
float: left;
margin: 10px;
color: #38a;
border-bottom: 1px dashed #888;
}
#site:hover {
color: #7af;
}
#close {
float: right;
margin: 10px;
}
#p {
font-family: Verdana, sans-serif;
position: absolute;
right: 10px;
bottom: 10px;
color: #adf;
border: 1px dashed #555;
padding: 4px 8px;
}
</style>
<img src="https://i.stack.imgur.com/Celmj.jpg" style="margin-top: -2000px; position: absolute;">
<canvas width="1360" height="376" style="margin-top: -2000px; position: absolute;"></canvas>
<script type="text/javascript">
/*
Copyright (c) 2013 lonely-pixel.com, Stuffit at codepen.io (http://codepen.io/stuffit)
View this and others at http://lonely-pixel.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
const mycanvas = document.querySelector('canvas');
const mycontext = mycanvas.getContext('2d');
// settings
var physics_accuracy = 5,
mouse_influence = 20,
mouse_cut = 6,
gravity = 900,
cloth_height = 30,
cloth_width = 50,
start_y = 20,
spacing = 7,
tear_distance = 60;
window.requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
var canvas,
ctx,
cloth,
boundsx,
boundsy,
mouse = {
down: false,
button: 1,
x: 0,
y: 0,
px: 0,
py: 0
};
window.onload = function() {
// ADDED TO BRING IN THE IMAGE
mycontext.clearRect(0, 0, mycanvas.width, mycanvas.height);
mycontext.drawImage(document.querySelector('img'), 0, 0, 1180, 376);
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
canvas.width = canvas.clientWidth;
canvas.height = 376;
canvas.onmousedown = function(e) {
mouse.button = e.which;
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
mouse.down = true;
e.preventDefault();
};
canvas.onmouseup = function(e) {
mouse.down = false;
e.preventDefault();
};
canvas.onmousemove = function(e) {
mouse.px = mouse.x;
mouse.py = mouse.y;
var rect = canvas.getBoundingClientRect();
mouse.x = e.clientX - rect.left,
mouse.y = e.clientY - rect.top,
e.preventDefault();
};
canvas.oncontextmenu = function(e) {
e.preventDefault();
};
boundsx = canvas.width - 1;
boundsy = canvas.height - 1;
ctx.strokeStyle = 'rgba(222,222,222,0.6)';
ctx.strokeStyle = 'magenta';
cloth = new Cloth();
update();
};
var Point = function(x, y) {
this.x = x;
this.y = y;
this.px = x;
this.py = y;
this.vx = 0;
this.vy = 0;
this.pin_x = null;
this.pin_y = null;
this.constraints = [];
//added - remember where this point was originally so we can get the right bit of the img
this.origx = x;
this.origy = y;
};
Point.prototype.update = function(delta) {
if (mouse.down) {
var diff_x = this.x - mouse.x,
diff_y = this.y - mouse.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
if (mouse.button == 1) {
if (dist < mouse_influence) {
this.px = this.x - (mouse.x - mouse.px) * 1.8;
this.py = this.y - (mouse.y - mouse.py) * 1.8;
}
} else if (dist < mouse_cut) this.constraints = [];
}
this.add_force(0, gravity);
delta *= delta;
nx = this.x + ((this.x - this.px) * .99) + ((this.vx / 2) * delta);
ny = this.y + ((this.y - this.py) * .99) + ((this.vy / 2) * delta);
this.px = this.x;
this.py = this.y;
this.x = nx;
this.y = ny;
this.vy = this.vx = 0
};
Point.prototype.draw = function() {
if (this.constraints.length <= 0) return;
var i = this.constraints.length;
while (i--) this.constraints[i].draw();
};
Point.prototype.resolve_constraints = function() {
if (this.pin_x != null && this.pin_y != null) {
this.x = this.pin_x;
this.y = this.pin_y;
return;
}
var i = this.constraints.length;
while (i--) this.constraints[i].resolve();
this.x > boundsx ? this.x = 2 * boundsx - this.x : 1 > this.x && (this.x = 2 - this.x);
this.y < 1 ? this.y = 2 - this.y : this.y > boundsy && (this.y = 2 * boundsy - this.y);
};
Point.prototype.attach = function(point) {
this.constraints.push(
new Constraint(this, point)
);
};
Point.prototype.remove_constraint = function(lnk) {
var i = this.constraints.length;
while (i--)
if (this.constraints[i] == lnk) this.constraints.splice(i, 1);
};
Point.prototype.add_force = function(x, y) {
this.vx += x;
this.vy += y;
};
Point.prototype.pin = function(pinx, piny) {
this.pin_x = pinx;
this.pin_y = piny;
};
var Constraint = function(p1, p2) {
this.p1 = p1;
this.p2 = p2;
this.length = spacing;
};
Constraint.prototype.resolve = function() {
var diff_x = this.p1.x - this.p2.x,
diff_y = this.p1.y - this.p2.y,
dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y),
diff = (this.length - dist) / dist;
if (dist > tear_distance) this.p1.remove_constraint(this);
var px = diff_x * diff * 0.5;
var py = diff_y * diff * 0.5;
this.p1.x += px;
this.p1.y += py;
this.p2.x -= px;
this.p2.y -= py;
};
let num = 0;
Constraint.prototype.draw = function() {
ctx.drawImage(mycanvas, this.p1.origx, this.p1.origy, spacing, spacing, this.p1.x, this.p1.y, spacing + 1, spacing + 1);
};
var Cloth = function() {
this.points = [];
var start_x = canvas.width / 2 - cloth_width * spacing / 2;
for (var y = 0; y <= cloth_height; y++) {
for (var x = 0; x <= cloth_width; x++) {
var p = new Point(start_x + x * spacing, start_y + y * spacing);
x != 0 && p.attach(this.points[this.points.length - 1]);
y == 0 && p.pin(p.x, p.y);
y != 0 && p.attach(this.points[x + (y - 1) * (cloth_width + 1)])
this.points.push(p);
}
}
};
Cloth.prototype.update = function() {
var i = physics_accuracy;
while (i--) {
var p = this.points.length;
while (p--) this.points[p].resolve_constraints();
}
i = this.points.length;
while (i--) this.points[i].update(.016);
};
Cloth.prototype.draw = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
var i = cloth.points.length;
while (i--) cloth.points[i].draw();
ctx.stroke();
};
function update() {
cloth.update();
cloth.draw();
requestAnimFrame(update);
}
</script>
</head>
<body>
<canvas id="c" width="800" height="376"> </canvas>
</body>
</html>
Note: it is possible to 'tear' the material with a right click and this facility probably needs removing - unless you want users to ruin the look of the cloth :)
I'm trying to code a snake game that will randomly move through the canvas. for now, I won't worry about the "food" as my main problem is the self-playing part not running. it seems to start but does not change course over time, so not sure if need to implement a timer (?)
Tried with a switch and thought by generating with random() one of the alternatives but only goes in one direction until hits the border
*/<-------------------------HTML----------------------->*/
<html>
<head>
<meta charset='utf-8'/>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class= 'game'>
<div id = 'home'>
<canvas id='mycanvas' width='350' height='350'>
</canvas>
</div>
<button id='btn'>START</button>
</div>
<script src="js/logic.js"></script>
</body>
</html>
CSS:
/*<----------------------CSS----------------------->*/
#home {
width: 350px;
height: 350px;
background-size: auto 350px;
background-repeat: no-repeat;
background-color: lightgrey;
background-position: center center;
padding: 0;
margin: 03;
}
button {
background-color: green;
color: white;
border: none;
bottom: 0;
height: 30px;
font-size: 12pt;
float: left;
width: 90px;
margin: 10px 0 0 0;
}
button:hover {
background-color: darkgreen;
}
button:disabled {
background-color: grey;
}
.game {
margin: 0 auto;
}
JS:
/*<-------------------JS----------------->*/
var mycanvas = document.getElementById('mycanvas');
var ctx = mycanvas.getContext('2d');
var snakeSize = 10;
var w = 350;
var h = 350;
var snake;
var snakeSize = 10;
var pixel;
var drawModule = (function() {
var bodySnake = function(x, y) {
ctx.fillStyle = 'green';
ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
ctx.strokeStyle = 'black';
ctx.strokeRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
}
var drawSnake = function() {
var length = 4;
snake = [];
for (var i = length - 1; i >= 0; i--) {
snake.push({ x: i, y: 0 });
}
}
var paint = function() {
ctx.fillStyle = 'lightgrey';
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = 'black';
ctx.strokeRect(0, 0, w, h);
btn.setAttribute('disabled', true);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
if (direction == 'right') {
snakeX++;
} else if (direction == 'left') {
snakeX--;
} else if (direction == 'up') {
snakeY--;
} else if (direction == 'down') {
snakeY++;
}
if (snakeX == -1 || snakeX == w / snakeSize || snakeY == -1 || snakeY == h / snakeSize || checkCollision(snakeX, snakeY, snake)) {
btn.removeAttribute('disabled', true);
ctx.clearRect(0, 0, w, h);
gameloop = clearInterval(gameloop);
return;
}
if (snakeX == pixel.x && snakeY == pixel.y) {
var tail = { x: snakeX, y: snakeY };
} else {
var tail = snake.pop();
tail.x = snakeX;
tail.y = snakeY;
}
snake.unshift(tail);
for (var i = 0; i < snake.length; i++) {
bodySnake(snake[i].x, snake[i].y);
}
}
var createPixels = function() {
pixel = {
x: Math.floor((Math.random() * 30) + 1),
y: Math.floor((Math.random() * 30) + 1)
}
}
var checkCollision = function(x, y, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].x === x && array[i].y === y) {
return true;
//this part should reinitiate the game
//when it hits an edge
/*}
if (x > w - 1 || x < 0 || y > h - 1 || h < 0) {
return true;*/
}
return false;
}
}
var init = function() {
var r = Math.round(Math.random() * 5);
switch (r) {
case 1:
direction = 'left';
console.log('left');
break;
case 2:
direction = 'right';
console.log('right');
break;
case 3:
direction = 'up';
console.log('up');
break;
case 4:
direction = 'down';
console.log('down');
break;
}
drawSnake();
createPixels();
gameloop = setInterval(paint, 80);
}
return {
init: init
};
}());
(function(window, document, undefined) {
var btn = document.getElementById('btn');
btn.addEventListener("click", function() { drawModule.init(); });
}
)(window, document, drawModule);
Assign direction a random value inside the paint() function.
Explanation: Currently, the only call to random() is in the init() function, which is only called once. Thus direction is only set once, and there is no way for it to change.
I am making an app for the Chrome Web Store. It is a clone of the Doodle Jump game. When I test and load it as an unpacked extension, this error keeps coming up.
Uncaught TypeError: Cannot read property 'getContext' of null
My code is here:
Javascript
function startGame() {
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = 422,
height = 552;
canvas.width = width;
canvas.height = height;
//Variables for game
var platforms = [],
image = document.getElementById("sprite"),
player, platformCount = 10,
position = 0,
gravity = 0.2,
animloop,
flag = 0,
menuloop, broken = 0,
dir, score = 0, firstRun = true;
//Base object
var Base = function() {
this.height = 5;
this.width = width;
//Sprite clipping
this.cx = 0;
this.cy = 614;
this.cwidth = 100;
this.cheight = 5;
this.moved = 0;
this.x = 0;
this.y = height - this.height;
this.draw = function() {
try {
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var base = new Base();
//Player object
var Player = function() {
this.vy = 11;
this.vx = 0;
this.isMovingLeft = false;
this.isMovingRight = false;
this.isDead = false;
this.width = 55;
this.height = 40;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 110;
this.cheight = 80;
this.dir = "left";
this.x = width / 2 - this.width / 2;
this.y = height;
//Function to draw it
this.draw = function() {
try {
if (this.dir == "right") this.cy = 121;
else if (this.dir == "left") this.cy = 201;
else if (this.dir == "right_land") this.cy = 289;
else if (this.dir == "left_land") this.cy = 371;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
this.jump = function() {
this.vy = -8;
document.getElementById('audio').innerHTML='<audio src="sounds/pup.mp3" preload="auto" autoplay autobuffer></audio>'
};
this.jumpHigh = function() {
this.vy = -16;
document.getElementById('audio').innerHTML='<audio src="sounds/high.mp3" preload="auto" autoplay autobuffer></audio>'
};
};
player = new Player();
//Platform class
function Platform() {
this.width = 70;
this.height = 17;
this.x = Math.random() * (width - this.width);
this.y = position;
position += (height / platformCount);
this.flag = 0;
this.state = 0;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 105;
this.cheight = 31;
//Function to draw it
this.draw = function() {
try {
if (this.type == 1) this.cy = 0;
else if (this.type == 2) this.cy = 61;
else if (this.type == 3 && this.flag === 0) this.cy = 31;
else if (this.type == 3 && this.flag == 1) this.cy = 1000;
else if (this.type == 4 && this.state === 0) this.cy = 90;
else if (this.type == 4 && this.state == 1) this.cy = 1000;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
//Platform types
//1: Normal
//2: Moving
//3: Breakable (Go through)
//4: Vanishable
//Setting the probability of which type of platforms should be shown at what score
if (score >= 5000) this.types = [2, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 2000 && score < 5000) this.types = [2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 1000 && score < 2000) this.types = [2, 2, 2, 3, 3, 3, 3, 3];
else if (score >= 500 && score < 1000) this.types = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
else if (score >= 100 && score < 500) this.types = [1, 1, 1, 1, 2, 2];
else this.types = [1];
this.type = this.types[Math.floor(Math.random() * this.types.length)];
//We can't have two consecutive breakable platforms otherwise it will be impossible to reach another platform sometimes!
if (this.type == 3 && broken < 1) {
broken++;
} else if (this.type == 3 && broken >= 1) {
this.type = 1;
broken = 0;
}
this.moved = 0;
this.vx = 1;
}
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
//Broken platform object
var Platform_broken_substitute = function() {
this.height = 30;
this.width = 70;
this.x = 0;
this.y = 0;
//Sprite clipping
this.cx = 0;
this.cy = 554;
this.cwidth = 105;
this.cheight = 60;
this.appearance = false;
this.draw = function() {
try {
if (this.appearance === true) ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
else return;
} catch (e) {}
};
};
var platform_broken_substitute = new Platform_broken_substitute();
//Spring Class
var spring = function() {
this.x = 0;
this.y = 0;
this.width = 26;
this.height = 30;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 45;
this.cheight = 53;
this.state = 0;
this.draw = function() {
try {
if (this.state === 0) this.cy = 445;
else if (this.state == 1) this.cy = 501;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var Spring = new spring();
function init() {
//Variables for the game
var dir = "left",
jumpCount = 0;
firstRun = false;
//Function for clearing canvas in each consecutive frame
function paintCanvas() {
ctx.clearRect(0, 0, width, height);
}
//Player related calculations and functions
function playerCalc() {
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true)
init();
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Gameover if it hits the bottom
if (base.y > height && (player.y + player.height) > height && player.isDead != "lol") {
player.isDead = true;
document.getElementById('audio').innerHTML='<audio src="sounds/gameover.mp3" preload="auto" autoplay autobuffer></audio>'
}
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
//Movement of player affected by gravity
if (player.y >= (height / 2) - (player.height / 2)) {
player.y += player.vy;
player.vy += gravity;
}
//When the player reaches half height, move the platforms to create the illusion of scrolling and recreate the platforms that are out of viewport...
else {
platforms.forEach(function(p, i) {
if (player.vy < 0) {
p.y -= player.vy;
}
if (p.y > height) {
platforms[i] = new Platform();
platforms[i].y = p.y - height;
}
});
base.y -= player.vy;
player.vy += gravity;
if (player.vy >= 0) {
player.y += player.vy;
player.vy += gravity;
}
score++;
}
//Make the player jump when it collides with platforms
collides();
if (player.isDead === true) gameOver();
}
//Spring algorithms
function springCalc() {
var s = Spring;
var p = platforms[0];
if (p.type == 1 || p.type == 2) {
s.x = p.x + p.width / 2 - s.width / 2;
s.y = p.y - p.height - 10;
if (s.y > height / 1.1) s.state = 0;
s.draw();
} else {
s.x = 0 - s.width;
s.y = 0 - s.height;
}
}
//Platform's horizontal movement (and falling) algo
function platformCalc() {
var subs = platform_broken_substitute;
platforms.forEach(function(p, i) {
if (p.type == 2) {
if (p.x < 0 || p.x + p.width > width) p.vx *= -1;
p.x += p.vx;
}
if (p.flag == 1 && subs.appearance === false && jumpCount === 0) {
subs.x = p.x;
subs.y = p.y;
subs.appearance = true;
jumpCount++;
}
p.draw();
});
if (subs.appearance === true) {
subs.draw();
subs.y += 8;
}
if (subs.y > height) subs.appearance = false;
}
function collides() {
//Platforms
platforms.forEach(function(p, i) {
if (player.vy > 0 && p.state === 0 && (player.x + 15 < p.x + p.width) && (player.x + player.width - 15 > p.x) && (player.y + player.height > p.y) && (player.y + player.height < p.y + p.height)) {
if (p.type == 3 && p.flag === 0) {
p.flag = 1;
jumpCount = 0;
return;
} else if (p.type == 4 && p.state === 0) {
player.jump();
p.state = 1;
} else if (p.flag == 1) return;
else {
player.jump();
}
}
});
//Springs
var s = Spring;
if (player.vy > 0 && (s.state === 0) && (player.x + 15 < s.x + s.width) && (player.x + player.width - 15 > s.x) && (player.y + player.height > s.y) && (player.y + player.height < s.y + s.height)) {
s.state = 1;
player.jumpHigh();
}
}
function updateScore() {
var scoreText = document.getElementById("score");
scoreText.innerHTML = score;
}
function gameOver() {
platforms.forEach(function(p, i) {
p.y -= 12;
});
if(player.y > height/2 && flag === 0) {
player.y -= 8;
player.vy = 0;
}
else if(player.y < height / 2) flag = 1;
else if(player.y + player.height > height) {
showGoMenu();
hideScore();
player.isDead = "lol";
}
}
//Function to update everything
function update() {
paintCanvas();
platformCalc();
springCalc();
playerCalc();
player.draw();
base.draw();
updateScore();
}
menuLoop = function(){return;};
animloop = function() {
update();
requestAnimFrame(animloop);
};
animloop();
hideMenu();
showScore();
}
function reset() {
hideGoMenu();
showScore();
player.isDead = false;
flag = 0;
position = 0;
score = 0;
base = new Base();
player = new Player();
Spring = new spring();
platform_broken_substitute = new Platform_broken_substitute();
platforms = [];
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
}
//Hides the menu
function hideMenu() {
var menu = document.getElementById("mainMenu");
menu.style.zIndex = -1;
}
//Shows the game over menu
function showGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = 1;
menu.style.visibility = "visible";
var scoreText = document.getElementById("go_score");
scoreText.innerHTML = "Ваш результат " + score + " очков!";
}
//Hides the game over menu
function hideGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = -1;
menu.style.visibility = "hidden";
}
//Show ScoreBoard
function showScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = 1;
}
//Hide ScoreBoard
function hideScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = -1;
}
function playerJump() {
player.y += player.vy;
player.vy += gravity;
if (player.vy > 0 &&
(player.x + 15 < 260) &&
(player.x + player.width - 15 > 155) &&
(player.y + player.height > 475) &&
(player.y + player.height < 500))
player.jump();
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true) {
init();
firstRun = false;
}
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
player.draw();
}
function update() {
ctx.clearRect(0, 0, width, height);
playerJump();
}
menuLoop = function() {
update();
requestAnimFrame(menuLoop);
};
menuLoop();
}
document.addEventListener("DOMContentLoaded", startGame, false);
<!DOCTYPE HTML>
<html>
<head>
<title>Doodle Jump</title>
<style type="text/css">
#import url(Gloria%20Hallelujah);
*{box-sizing: border-box;}
body {
margin: 0; padding: 0;
font-family: 'Gloria Hallelujah', cursive;
}
.container {
height: 552px;
width: 422px;
position: relative;
margin: 20px auto;
overflow: hidden;
}
canvas {
height: 552px;
width: 422px;
display: block;
background: url(images/Y0BMP.png) top left;
}
#scoreBoard {
width: 420px;
height: 50px;
background: rgba(182, 200, 220, 0.7);
position: absolute;
top: -3px;
left: 0;
z-index: -1;
border-image: url(images/5BBsR.png) 100 5 round;
}
#scoreBoard p {
font-size: 20px;
padding: 0;
line-height: 47px;
margin: 0px 0 0 5px;
}
img {display: none}
#mainMenu, #gameOverMenu {
height: 100%;
width: 100%;
text-align: center;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
#gameOverMenu {
visibility: hidden;
}
h2, h3, h1 {font-weight: normal}
h1 {
font-size: 60px;
color: #5a5816;
transform: rotate(-10deg);
margin: 0px;
}
h3 {text-align: right; margin: -10px 20px 0 0; color: #5e96be}
h3 a {color: #5a5816}
.button {
width: 105px;
height: 31px;
background: url(images/2WEhF.png) 0 0 no-repeat;
display: block;
color: #000;
font-size: 12px;
line-height: 31px;
text-decoration: none;
position: absolute;
left: 50%;
bottom: 50px;
margin-left: -53px;
}
.info {position: absolute; right: 20px; bottom: 00px; margin: 0; color: green}
.info .key {
width: 16px;
height: 16px;
background: url(images/2WEhF.png) no-repeat;
text-indent: -9999px;
display: inline-block;
}
.info .key.left {background-position: -92px -621px;}
.info .key.right {background-position: -92px -641px;}
</style>
</head>
<body><div style="position:absolute;z-index:999;padding:10px;top:0;right:0;background:#000" id="sxz03">
<div style="float:right;padding-left:10px"><img onclick="document.getElementById('sxz03').style.display='none'" src="images/x.gif" width="15" alt="" /></div>
<br>
<div style="position:absolute;top:-100px"></div>
</div>
<div class="container">
<canvas id="canvas"></canvas>
<div id="mainMenu">
<h1>doodle jump</h1>
<h3>A HTML5 game</h3>
<a class="button" href="javascript:init()">Play</a>
</div>
<div id="gameOverMenu">
<h1>Game Over!</h1>
<h3 id="go_score">Your score was ...</h3>
<a class="button" href="javascript:reset()">Play Again</a>
</div>
<!-- Preloading image ;) -->
<img id="sprite" src="images/2WEhF.png"/>
<div id="scoreBoard">
<p id="score">0</p>
</div>
</div>
<div id="audio"></div>
<script src="jquery.min.js"></script>
<script src="game.js"></script>
</body>
</html>
So when I run this, the intro works, but when I click the play button, nothing happens. If you want to run this code, I will put a download link for the folder that I used in this question.
I've tried CSS cursor property
How to create a cursor like this webpage
https://my.pottermore.com/patronus
You can create such effects using css and JavaScript:
var standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
var nav = (!document.all || window.opera);
var tmr = null;
var spd = 50;
var x = 0;
var x_offset = 5;
var y = 0;
var y_offset = 15;
document.onmousemove = get_mouse;
function get_mouse(e)
{
x = (nav) ? e.pageX : event.clientX+standardbody.scrollLeft;
y = (nav) ? e.pageY : event.clientY+standardbody.scrollTop;
x += x_offset;
y += y_offset;
beam(1);
}
function beam(n)
{
if(n<5)
{
document.getElementById('div'+n).style.top=y+'px'
document.getElementById('div'+n).style.left=x+'px'
document.getElementById('div'+n).style.visibility='visible'
n++;
tmr=setTimeout("beam("+n+")",spd);
}
else
{
clearTimeout(tmr);
fade(4);
}
}
function fade(n)
{
if(n>0)
{
document.getElementById('div'+n).style.visibility='hidden'
n--;
tmr=setTimeout("fade("+n+")",spd);
}
else clearTimeout(tmr);
}
body{
overflow-x:hidden;
}
.s1
{
position : absolute;
font-size : 10pt;
color : blue;
visibility: hidden;
}
.s2
{
position : absolute;
font-size : 18pt;
color : red;
visibility : hidden;
}
.s3
{
position : absolute;
font-size : 14pt;
color : gold;
visibility : hidden;
}
.s4
{
position : absolute;
font-size : 12pt;
color : lime;
visibility : hidden;
}
<div id="div1" class="s1">*</div>
<div id="div2" class="s2">*</div>
<div id="div3" class="s3">*</div>
<div id="div4" class="s4">*</div>
This code can be found at: http://www.javascriptkit.com/script/script2/sparkler.shtml
OR if you do not want to use any HTML elements for your mouse trails you can use the following CSS and JS:
var dots = [],
mouse = {
x: 0,
y: 0
};
var Dot = function() {
this.x = 0;
this.y = 0;
this.node = (function(){
var n = document.createElement("div");
n.className = "tail";
document.body.appendChild(n);
return n;
}());
};
Dot.prototype.draw = function() {
this.node.style.left = this.x + "px";
this.node.style.top = this.y + "px";
};
for (var i = 0; i < 12; i++) {
var d = new Dot();
dots.push(d);
}
function draw() {
var x = mouse.x,
y = mouse.y;
dots.forEach(function(dot, index, dots) {
var nextDot = dots[index + 1] || dots[0];
dot.x = x;
dot.y = y;
dot.draw();
x += (nextDot.x - dot.x) * .6;
y += (nextDot.y - dot.y) * .6;
});
}
addEventListener("mousemove", function(event) {
mouse.x = event.pageX;
mouse.y = event.pageY;
});
function animate() {
draw();
requestAnimationFrame(animate);
}
animate();
.tail {
position: absolute;
height: 6px; width: 6px;
border-radius: 3px;
background: tomato;
}
This Code Can be found at : https://codepen.io/falldowngoboone/pen/PwzPYv
function saveSettings(form){
document.cookie = "cWidth=" + form.cWidth.value + ";cHeight=" + form.cHeight.value + ";bSpeed=" + form.bSpeed.value + ";pSpeed=" + form.pSpeed.value + ";pHeight=" + form.pHeight.value + "playTo=" + form.playTo.value + ";" + "movePlayer1Up=" + form.movePlayer1Up.value + ";" + ";movePlayer1Down=" + form.movePlayer1Down.value +";movePlayer2Up=" + form.movePlayer2Up.value + ";movePlayer2Down=" + form.movePlayer2Down.value;
}
function loadSettings(form){
form.cWidth.value = getCookie('cWidth');
form.cHeight.value = getCookie('cHeight');
form.bSpeed.value = getCookie('bSpeed');
form.pSpeed.value = getCookie('pSpeed');
form.pHeight.value = getCookie('pHeight');
form.playTo.value = getCookie('playTo');
form.movePlayer1Up.value = getCookie('movePlayer1Up');
form.movePlayer1Down.value = getCookie('movePlayer1Down');
form.movePlayer2Up.value = getCookie('movePlayer2Up');
form.movePlayer2Down.value = getCookie('movePlayer2Down');
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
<input type = "button" name = "saveSettings1" value = "Save to #1" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px; position: absolute; font-size: 9px;" onClick = "saveSettings(this.form);">
<input type = "button" name = "loadSettings1" value = "Load #1" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px;position: absolute; font-size: 9px;margin-left: 44px;" onClick = "loadSettings(this.form)">
I am in the process of making a pong game and after making a complicated settings menu, I have encountered a problem; whenever the page is reloaded, all information is lost and the data is reset to the default. I thought of using a submit or some sort of button in the form to save the data but have no experience with php and thus am stuck. This is my game for context. Currently, I am trying to get the bottom right four
function saveSettings(form){
document.cookie = "cWidth=form.cWidth.value;cHeight=form.cHeight.value;bSpeed=form.bSpeed.value;pSpeed=form.pSpeed.value;pHeight=form.pHeight.value;playTo=form.playTo.value;movePlayer1Up=form.movePlayer1Up.value;movePlayer1Down=form.movePlayer1Down.value;movePlayer2Up=form.movePlayer2Up.value;movePlayer2Down=form.movePlayer2Down.value;";
}
function loadSettings(form){
form.cWidth.value = getCookie('cWidth');
form.cHeight.value = getCookie('cHeight');
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
buttons on the settings screen to actually do something
Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Pong Game by ME</title>
<style>
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body style = "text-align:center; font-size:25px;">
<script>
function playGame(form){
document.getElementById("Settings").style.display = 'none';
var canvas;
var ctx;
var keystate;
var canvasWidth = parseInt(form.cWidth.value);
var canvasHeight = parseInt(form.cHeight.value);
var ballSpeed = parseInt(form.bSpeed.value);
var playerSpeed = parseInt(form.pSpeed.value);
var playerHeight = parseInt(form.pHeight.value);
var playTo = parseInt(form.playTo.value);
var movePlayer1Up = form.movePlayer1Up.value.charCodeAt(0) - 32;
var movePlayer1Down = form.movePlayer1Down.value.charCodeAt(0) - 32;
if (form.movePlayer2Up.value == "UpArrow"){
var movePlayer2Up = 38;
}
else{
var movePlayer2Up = form.movePlayer2Up.value.charCodeAt(0) - 32;
}
if (form.movePlayer2Down.value == "DownArrow"){
var movePlayer2Down = 40;
}
else{
var movePlayer2Down = form.movePlayer2Down.value.charCodeAt(0) - 32;
}
var player1 = {
x: null,
y: null,
score: null,
width: 20,
height: playerHeight,
update: function() {
if (keystate[movePlayer1Up]) this.y -= playerSpeed;
if (keystate[movePlayer1Down]) this.y -= -playerSpeed;
this.y = Math.max(Math.min(this.y, canvasHeight - this.height), 0);
},
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
var player2 = {
x: null,
y: null,
score: null,
width: 20,
height: playerHeight,
update: function() {
if (keystate[movePlayer2Up]) this.y -= playerSpeed;
if (keystate[movePlayer2Down]) this.y += playerSpeed;
this.y = Math.max(Math.min(this.y, canvasHeight - this.height), 0);
},
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
var ball = {
x: null,
y: null,
vel: null,
side: 20,
serve: function(side) {
var r = Math.random();
this.x = canvasWidth/2;
this.y = (canvasHeight - this.side) * r ;
var phi = 0.1 * Math.PI * (1 - 2 * r);
this.vel = {
x: side * ballSpeed * Math.cos(phi),
y: ballSpeed * Math.sin(phi)
}
},
update: function() {
this.x += this.vel.x;
this.y += this.vel.y;
if (0 > this.y || this.y + this.side > canvasHeight) {
var offset = this.vel.y < 0 ? 0 - this.y : canvasHeight - (this.y + this.side);
this.y += 2 * offset;
this.vel.y *= -1;
}
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx + bw && ay < by + bh && bx < ax + aw && by < ay + ah;
};
var pdle = this.vel.x < 0 ? player1 : player2;
if (AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height,
this.x, this.y, this.side, this.side)
) {
this.x = pdle === player1 ? player1.x + player1.width : player2.x - this.side;
var n = (this.y + this.side - pdle.y)/(pdle.height + this.side);
var phi = 0.25 * Math.PI * (2 * n - 1);
var smash = Math.abs(phi) > 0.2 * Math.PI ? 1.5 : 1;
this.vel.x = smash * (pdle === player1 ? 1 : -1) * ballSpeed * Math.cos(phi);
this.vel.y = smash * ballSpeed * Math.sin(phi);
ballSpeed += 1;
}
if (0 > this.x + this.side || this.x > canvasWidth) {
ballSpeed = parseInt(form.bSpeed.value);
var isplayer1 = pdle === player1;
player1.score += isplayer1 ? 0 : 1;
player2.score += isplayer1 ? 1 : 0;
this.serve(pdle === player1 ? 1 : -1);
}
},
draw: function() {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
function mplayer2n() {
canvas = document.createElement("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
player1.x = player1.width;
player1.y = (canvasHeight - player1.height)/2;
player2.x = canvasWidth - (player1.width + player2.width);
player2.y = (canvasHeight - player2.height)/2;
player1.score = 0;
player2.score = 0;
ball.serve(1);
}
function update() {
if (player1.score < 10 && player2.score < 10){
ball.update();
player1.update();
player2.update();
}
}
function draw() {
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.save();
ctx.fillStyle = "red";
player1.draw();
ctx.fillStyle = "blue";
player2.draw();
ctx.fillStyle = "white";
ball.draw();
var w = 4;
var x = (canvasWidth - w) * 0.5;
var y = 0;
var step = canvasHeight/20;
while (y < canvasHeight) {
ctx.fillStyle = "white"
ctx.fillRect(x, y + step * 0.25, w, step * 0.5);
y += step;
}
ctx.font="150px Georgia"
var t = player1.score
var v = player2.score
ctx.fillText(t, canvas.width/2 - ctx.measureText(t).width - 20, 100);
ctx.fillText(v, canvas.width/2 + 20, 100)
if (player1.score > playTo - 1){
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "Black"
ctx.font= "100px Georgia"
var u = t + " - " + v
var w = "Player 1 wins"
ctx.fillText(w, canvas.width/2 - ctx.measureText(w).width/2, 130);
ctx.font = "150px Georgia"
ctx.fillText(u, canvas.width/2 - ctx.measureText(u).width/2, 300);
}
else if (player2.score > playTo - 1){
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.fillStyle = "Black"
ctx.font= "100px Georgia"
var u = t + " - " + v
var w = "Player 2 wins"
ctx.fillText(w, canvas.width/2 - ctx.measureText(w).width/2, 130);
ctx.font = "150px Georgia"
ctx.fillText(u, canvas.width/2 - ctx.measureText(u).width/2, 300);
}
ctx.restore();
}
mplayer2n();
}
</script>
<!-- CANCEROUS CSSING BELOW: BE CAREFULL -->
<form action = "" id = "Settings">
<h1 style="text-decoration:underline;margin-top: 2px;margin-bottom: 20px">Settings:</h1>
Field Length:
<input oninput = "cWidthOut.value = cWidth.value" type = "range" name = "cWidth" min = "700" value = "1200" max = "1400" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "cWidthOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 1200</p>
Field Height:
<input oninput = "cHeightOut.value = cHeight.value" type = "range" name = "cHeight" min = "300" value = "600" max = "700" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "cHeightOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 600</p>
Ball Speed:
<input oninput = "bSpeedOut.value = bSpeed.value" type = "range" name = "bSpeed" min = "5" value = "10" max = "20" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "bSpeedOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 10</p>
Paddle Speed:
<input oninput = "pSpeedOut.value = pSpeed.value" type = "range" name = "pSpeed" min = "6" value = "12" max = "14" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "pSpeedOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 12</p>
Paddle Length:
<input oninput = "pHeightOut.value = pHeight.value" type = "range" name = "pHeight" min = "50" value = "100" max = "200" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "pHeightOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 100</p>
First to ___ Points:
<input oninput = "playToOut.value = playTo.value" type = "range" name = "playTo" min = "5" value = "10" max = "25" style = "font-size: 20px; margin-left:5px;background-color:lightgrey"><output style = "margin-left: 10px; font-size: 20px;"name = "playToOut"></output><p style = "font-size: 10px; margin-top: 5px;">Default: 10</p>
Left Side Up:
<input type = "text" name = "movePlayer1Up" value = "w" style = "font-size: 20px; margin-left:5px;background-color:lightgrey; width:110px"> <br>
<p style = "font-size:10px"> This must be a normal key or up/down arrow </p>
Left Side Down:
<input type = "text" name = "movePlayer1Down" value = "s" style = "font-size: 20px; margin-left:5px;background-color:lightgrey; width:110px""><br>
<p style = "font-size:10px"> This must be a normal key or up/down arrow </p>
Right Side Up:
<input type = "text" name = "movePlayer2Up" value = "UpArrow" style = "font-size: 20px; margin-left:5px;background-color:lightgrey; width:110px"><br>
<p style = "font-size:10px"> This must be a normal key or up/down arrow </p>
Right Side Down:
<input type = "text" name = "movePlayer2Down" value = "DownArrow" style = "font-size: 20px; margin-left:5px;background-color:lightgrey; width:110px"><br>
<p style = "font-size:10px"> This must be a normal key or up/down arrow </p>
<input type = "button" name = "Start" value = "Start" style = "font-size:40px;border:none;color:black;background-color:lightpink; border-radius: 10px; position: absolute; margin-left: -105px;" onClick = "playGame(this.form)">
<input type = "button" name = "saveSettings1" value = "Save to #1" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px; position: absolute; font-size: 9px;">
<input type = "button" name = "saveSettings2" value = "Save to #2" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px; position: absolute; font-size: 9px;;margin-top: 28px;">
<input type = "button" name = "loadSettings1" value = "Load #1" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px;position: absolute; font-size: 9px;margin-left: 44px;">
<input type = "button" name = "loadSettings2" value = "Load #2" style = "font-size:20px;border:none;color:black;background-color:lightblue; border-radius: 3px; white-space: normal; width:40px; height: 25px; position: absolute; font-size: 9px;margin-left: 44px;margin-top: 28px;">
</form>
</body>
</html>
Creating a cookie
Since there's no sensitive information here, you could store a cookie.
playerHeight = 30;
playerWidth = 10;
document.cookie = "pHeight=" + playerHeight;
document.cookie = "pWidth=" + playerWidth;
Reading a cookie
To read the cookie http://www.w3schools.com/js/js_cookies.asp:
The cname is for example pHeight or pWidth.
The function below can be used: getCookie("pHeight") = "30"
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
Save Button
To create a save button try:
document.getElementById("btnsave").addEventListener("click", saveSettings);
Convenient jsFiddle
https://jsfiddle.net/198z9nk9/10/