Making JS game, where to add other objects into code - javascript

I have a game concept and using w3 schools i have built the basic code for a moving game piece at the base of the canvas. I want to build a game different to the W3 games plan though. I'm not asking for help actually writing code, I'm asking for help on where in my code to add other variables/objects. Here is my current code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
canvas {
border: 5px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
myGamePiece = new component(30, 30, "black", 350, 445);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 700;
this.canvas.height = 480;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
}
myGamePiece.newPos();
myGamePiece.update();
}
</script>
</body>
</html>
Any help would be appreciated please and thank you.
For anyone interested my plan is to have different objects falling from top and as you catch them each one has a different effect on your player or the background/music.

On that code to add other objects, you will need to insert code in two places:
function startGame
This is where all the object variables are initialized
function updateGameArea
Here is where the object actually gets drawn into the canvas
So let's jump to an example:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
canvas {
border: 5px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
dots = []
for (i = 0; i < 45; i++) {
a = i*8 * Math.PI / 180
dots.push(new component(2, 2, "red", Math.sin(a)*45 + 80, Math.cos(a)*35 + 60))
}
myGamePiece = new component(30, 30, "black", 350, 125);
myGameArea.start();
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 600;
this.canvas.height = 160;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
});
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
});
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
}
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
}
myGamePiece.newPos();
myGamePiece.update();
dots.forEach(x => x.update());
}
</script>
</body>
</html>
function startGame
I added dots = []... just a few "dot" on a elliptical pattern
function updateGameArea
And here we just call the update on the objects:
dots.forEach(x => x.update());

Related

HTML Canvas gun function

I need help finishing a function that shoots bullets after pressing 'space'.
I tried using these
var b = new bullet();
var bullets = []
bullets.push(b)
Then a for loop like this:
for (var i = 0; i < 6; i++) {
but I cant get it to work. Basically a function that every time a bullet is made, it is stored in an array then space loops through the array making new bullets on space press.
fiddle: https://jsfiddle.net/tmanrocks999/7mLpo8uj/652/
code:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullet;
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 0, 240);
endGoalPiece = new component(30, 30, "black", 450, 240);
myEnemy1 = new component(30, 30, "green", 200, 240);
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
//this.gravity = 0.05;
//this.gravitySpeed = 0;
this.x = x;
this.y = y;
this.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY; //+ this.gravitySpeed;
}
}
}
function jump() {
myGamePiece.gravitySpeed=-1;
}
}
function shootGun(){
bullet = new component(11, 5, "blue", myGamePiece.x+27 , myGamePiece.y+13 );
bullet.newPos();
bullet.speedX=1;
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myGamePiece.speedX = -1; }//left
if (myGameArea.key && myGameArea.key == 39) {myGamePiece.speedX = 1; }//right
if (myGameArea.key && myGameArea.key == 38) {myGamePiece.gravitySpeed = -1; }//jump
if (myGameArea.key && myGameArea.key == 32) {shootGun()}//shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullet.newPos();
bullet.update();
}
</script>
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>
</body>
</html>
I expect on space press for bullets to keep being created by looping through the array but at the moment after space press only 1 bullet is made and position is reset every time you press space ( I know why this is I don't need it explained).
How can I get the illusion of a shooter.
Take a look at this code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>STACKOVERFLOW</title>
<style>
canvas {
border: 4px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<p>use the arrow keys on you keyboard to move the red square.</p>
<span id="myEnemy1Hp">10</span> <br>
<span id="playerExp">0<span><br> / <span id = "playerMaxExp">100</span>
<script>
var myGamePiece;
var endGoalPiece;
var myEnemy1;
var bullets = [];
var myEnemy1Hp = 10;
var damage = 1;
var playerExp = 0;
function startGame() {
myGameArea.start();
myGamePiece = new component(30, 30, "red", 0, 240);
endGoalPiece = new component(30, 30, "black", 450, 240);
myEnemy1 = new component(30, 30, "green", 200, 240);
}
var myGameArea = {
canvas: document.createElement("canvas"),
start: function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e) {
myGameArea.key = false;
})
},
clear: function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y) {
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
//this.gravity = 0.05;
//this.gravitySpeed = 0;
this.x = x;
this.y = y;
this.color = color;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY; //+ this.gravitySpeed;
}
}
function jump() {
myGamePiece.gravitySpeed = -1;
}
function shootGun() {
let bullet = new component(11, 5, "blue", myGamePiece.x + 27, myGamePiece.y + 13);
bullet.newPos();
bullet.speedX = 1;
bullets.push( bullet );
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {
myGamePiece.speedX = -1;
} //left
if (myGameArea.key && myGameArea.key == 39) {
myGamePiece.speedX = 1;
} //right
if (myGameArea.key && myGameArea.key == 38) {
myGamePiece.gravitySpeed = -1;
} //jump
if (myGameArea.key && myGameArea.key == 32) {
shootGun()
} //shoot gun
//if (myGameArea.key && myGameArea.key == 40) {myGamePiece.speedY = 1; }// down
myEnemy1.update();
endGoalPiece.update();
myGamePiece.newPos();
myGamePiece.update();
bullets.forEach( (bullet)=> {
bullet.newPos()
bullet.update();
});
// bullet.newPos();
// bullet.update();
}
</script>
</body>
</html>
Codepen

A simple Javascript game called Traceball

I need help/advice on how to sort out an issue I have
https://raw.githubusercontent.com/TalvinJoshuaJacobs/TraceBall/master/src
My task is to code a game in Javascript and HTML where the user has to escape an enemy.
I am struggling with telling the the red box "obstacle" to follow me (the green box)
Any suggestions?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:20px solid #000000;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(130, 130, "green", 10, 120);
myObstacle = new component(130, 130, "red", 300, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1550;
this.canvas.height = 872;
this.canvas.style.cursor = "none";
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousemove', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
myGamePiece.x = myGameArea.x;
myGamePiece.y = myGameArea.y;
}
myObstacle.x -= 5;
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
</script>
<p>Avoid hitting the obstacle, or else the game will stop.</p>
</body>
</html>
If you're looking for implementation suggestions, you should look into event sourcing. You could make your game piece an event emitter and trigger an event that will move your obstacle when the event is fired.
If you're using a bundler like webpack or something similar you can use the nodejs EventEmitter, but that's not available in the browser by default.
https://www.npmjs.com/package/EventEmitter
Check out this repo for a naive implementation of an event emitter that can be used in the browser: https://github.com/parallaxisjones/microevent.js
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:20px solid #000000;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
function startGame() {
myGamePiece = new component(130, 130, "green", 10, 120);
myObstacle = new component(130, 130, "red", 300, 120);
myGamePiece.on('move', function(params){
// do something with myObstacle
myObstacle.updatePosition(params);
})
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1550;
this.canvas.height = 872;
this.canvas.style.cursor = "none";
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('mousemove', function (e) {
myGameArea.x = e.pageX;
myGameArea.y = e.pageY;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
//fire an event that can be subscribed to by other things
this.trigger('move', this)
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
// register components as an event emitter with the microevent lib linked
MicroEvent.mixin(component)
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGameArea.clear();
if (myGameArea.x && myGameArea.y) {
myGamePiece.x = myGameArea.x;
myGamePiece.y = myGameArea.y;
}
myObstacle.x -= 5;
myObstacle.update();
myGamePiece.newPos();
myGamePiece.update();
}
}
</script>
<p>Avoid hitting the obstacle, or else the game will stop.</p>
</body>
</html>

Jumping on canvas

I can't figure out how I can make myGamePiece jump using the up-key. First I tried the simple "myGamePiece.speedY = 1", but this doesn't work. Nor does trying to reverse "this.gravitySpeed" in the function. Can someone help me and if possible explain why mine don't work and yours does? Thanks in advance! My excuses if it seems to long, I'm unable to shorten it even further without removing the code of the component.
A litle explaination for the code:
function startGame: Starts the game
var myGameArea: Allows to multiply press two keys
function component: generates the object and its characteristics
function updateGameArea: Allows for the movement of the object
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
function startGame() {
myGamePiece = new component(30, 30, "red", 80, 75);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = true;
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -2; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 2; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
myGamePiece.newPos();
myGamePiece.update();
}
</script>
</body>
</html>
The problem is that the value of the gravitySpeed variable is constantly increasing.
Try to reset the gravitySpeed variable value to 0 in your hitBottom check:
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
You may also want to view values of some parameters in real time while you debugging:
add a block like this to your html
<div style="position:absolute; width: 300px; bottom: 50px; right: 50px;">
<p>sppedY: <span id="speedY"></span></p>
<p>gravitySpeed: <span id="gravitySpeed"></span></p>
<p>posY: <span id="posY"></span></p>
</div>
and a block like this in your updateGameArea function
...
myGamePiece.newPos();
// -- debug --
speedY.innerText = myGamePiece.speedY.toFixed(2);
gravitySpeed.innerText = myGamePiece.gravitySpeed.toFixed(2);
posY.innerText = myGamePiece.y.toFixed(2);
// -----------
myGamePiece.update();

How to add innerHTML to an existing attribute

I want to add a <button> to a canvas, and I thought adding it like this may work, but it doesn't!! How do you add a <button> element to innerHTML inside a canvas?
Earlier (in case this helps,):
ctx = myGameArea.context;
<script>
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
//this next part doesn't work!!!
ctx.innerHTML = ("<button onclick='startGame()'>Restart</button>");
}
}
</script>
For full code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
var transitionBlock;
var blockTransition;
function startGame() {
myGamePiece = new component(40, 40, "#00ff00ff", 50, 140);
myObstacle = new component(80, 37, "#cf0000ff", 240, 0);
transitionBlock=new component(10, 80, "#f1f1f1ff", 590, 120);
blockTransition=new component(10, 80, "#f1f1f1ff", -40, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 560;
this.canvas.height = 320;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGamePiece.update();
myGameArea.clear();
myObstacle.update()
transitionBlock.update();
blockTransition.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
}
if (myGameArea.key && myGameArea.key == 37||myGameArea.key && myGameArea.key == 65) {myGamePiece.speedX = -3; } else if (myGameArea.key && myGameArea.key == 39||myGameArea.key && myGameArea.key == 68) {myGamePiece.speedX = 3; } else if (myGameArea.key && myGameArea.key == 38||myGameArea.key && myGameArea.key == 87) {myGamePiece.speedY = -3; } else if (myGameArea.key && myGameArea.key == 40||myGameArea.key && myGameArea.key == 83) {myGamePiece.speedY = 3; } else {myGamePiece.speedX = 0; myGamePiece.speedY = 0;}
myGamePiece.update();
}
</script>
</body>
</html>
HTML inside a canvas is not possible , however what you can do is to give your button an absolute position on the top of your canvas.
Here is a small example:
button{
position:absolute;
left:100px;
top:50px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacle;
var transitionBlock;
var blockTransition;
function startGame() {
myGamePiece = new component(40, 40, "#00ff00ff", 50, 140);
myObstacle = new component(80, 37, "#cf0000ff", 240, 0);
transitionBlock=new component(10, 80, "#f1f1f1ff", 590, 120);
blockTransition=new component(10, 80, "#f1f1f1ff", -40, 120);
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 560;
this.canvas.height = 320;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function (e) {
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
stop : function() {
clearInterval(this.interval);
ctx.fillStyle="red";
ctx.font="80px Georgia";
ctx.fillText("You died",125,120);
}
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
if (myGamePiece.crashWith(myObstacle)) {
myGameArea.stop();
} else {
myGamePiece.update();
myGameArea.clear();
myObstacle.update()
transitionBlock.update();
blockTransition.update();
myGamePiece.x += myGamePiece.speedX;
myGamePiece.y += myGamePiece.speedY;
}
if (myGameArea.key && myGameArea.key == 37||myGameArea.key && myGameArea.key == 65) {myGamePiece.speedX = -3; } else if (myGameArea.key && myGameArea.key == 39||myGameArea.key && myGameArea.key == 68) {myGamePiece.speedX = 3; } else if (myGameArea.key && myGameArea.key == 38||myGameArea.key && myGameArea.key == 87) {myGamePiece.speedY = -3; } else if (myGameArea.key && myGameArea.key == 40||myGameArea.key && myGameArea.key == 83) {myGamePiece.speedY = 3; } else {myGamePiece.speedX = 0; myGamePiece.speedY = 0;}
myGamePiece.update();
}
</script>
<button>Hello I am a button floating on the top of the canvas</button>
</body>
</html>
As you can see in the example the button is floating over the canvas, but not inside it.
<div style="position: relative;">
<canvas style="width:300px; height: 300px;" />
<button style="position:absolute; top: 50%; left: 50%>hello</button>
</div>

Trouble Displaying Canvas in Basic HTML Canvas Game

I am trying to create a basic HTML game using the Canvas element, but I am having trouble with it. Unfortunately, I don't know where the error is in my code, so I have posted the entirety of the document I'm working on below.
My problem: The canvas is not displaying when I run the HTML document.
This code's based off of (as in it pretty much is) the Movement tutorial from w3schools for using the Canvas, available at https://www.w3schools.com/graphics/tryit.asp?filename=trygame_movement_keyboard, but when chaing variable names I must've broken something, because after looking at this for hours I can't figure out what I'm missing.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload = "initial()">
<script>
var playerOne;
function initial() {
playerOne = new canvasObject(30, 30, "red", 225, 225);
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas");
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function canvasObject(width, height, color, x, y, type)
{
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = gameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
gameArea.clear();
playerOne.moveAngle = 0;
playerOne.speed = 0;
if (gameArea.keys && gameArea.keys[37]) {
playerOne.moveAngle = -1;
}
if (gameArea.keys && gameArea.keys[39]) {
playerOne.moveAngle = 1;
}
if (gameArea.keys && gameArea.keys[38]) {
playerOne.speed= 1;
}
if (gameArea.keys && gameArea.keys[40]) {
playerOne.speed= -1;
}
playerOne.newPos();
playerOne.update();
}
</script>
</body>
</html>
gameArea is an object. Object properties are separated with ,, not ;. Hence, there is a syntax error after the definition of canvas.
var playerOne;
function initial() {
playerOne = new canvasObject(30, 30, "red", 225, 225);
gameArea.start();
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
e.preventDefault();
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
stop : function() {
clearInterval(this.interval);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function canvasObject(width, height, color, x, y, type)
{
this.type = type;
this.width = width;
this.height = height;
this.speed = 0;
this.angle = 0;
this.moveAngle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = gameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
function updateGameArea() {
gameArea.clear();
playerOne.moveAngle = 0;
playerOne.speed = 0;
if (gameArea.keys && gameArea.keys[37]) {
playerOne.moveAngle = -1;
}
if (gameArea.keys && gameArea.keys[39]) {
playerOne.moveAngle = 1;
}
if (gameArea.keys && gameArea.keys[38]) {
playerOne.speed= 1;
}
if (gameArea.keys && gameArea.keys[40]) {
playerOne.speed= -1;
}
playerOne.newPos();
playerOne.update();
}
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload = "initial()">
You have a syntax error:
var gameArea = {
canvas : document.createElement("canvas");
...
}
You've used ; instead of ,

Categories