Question:
Why is the requestAnimationFrame called with this function? For example, if I was building a game what benefit would requestAnimationFrame be over just repainting the canvas.
code:
function main() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
All Code Below: (You would need 3 .jpg files)
<html>
<head>
<title>test</title>
</head>
<body>
<script>
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "monster.png";
// Game objects
var hero = {
speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (hero.x <= (monster.x + 32) &&
monster.x <= (hero.x + 32) &&
hero.y <= (monster.y + 32) &&
monster.y <= (hero.y + 32)
) {
++monstersCaught;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Goblins caught: " + monstersCaught, 32, 32);
};
// The main game loop
/*var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};*/
// The main game loop -- This is the second way of doing this
function main() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
var then = Date.now();
reset();
main();
</script>
</body>
</html>
Because repeatedly calling main would cause the browser to hang until it gave up with a stack overflow error.
requestAnimationFrame simply says "do this when the browser is ready to render another frame".
Related
I'm developing a game and I was wondering why isn't the "crab" (an entity) killable like the "monster" (also an entity). What I mean is that if I touch the goblin monster, I get a point, but I just walk across the crab.
I attempted to add an if..else, but then the player got thousands of points per second.
What have I done wrong?
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function() {
bgReady = true;
};
bgImage.src = "images/background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function() {
heroReady = true;
};
heroImage.src = "images/hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function() {
monsterReady = true;
};
monsterImage.src = "images/monster.png";
// Crab image
var crabReady = false;
var crabImage = new Image();
crabImage.onload = function() {
crabReady = true;
};
crabImage.src = "images/old/hero.png";
// Game objects
var hero = {
speed: 300 // movement in pixels per second
};
var monster = {};
var crab = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function(e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function() {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
// Throw the crab somewhere on the screen randomly
crab.x = 32 + (Math.random() * (canvas.width - 64));
crab.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function(modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (
hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)
) {
++monstersCaught;
reset();
}
};
// Draw everything
var render = function() {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
if (crabReady) {
ctx.drawImage(crabImage, crab.x, crab.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Mobs killed: " + monstersCaught, 32, 32);
};
// The main game loop
var main = function() {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
var then = Date.now();
reset();
main();
<!DOCTYPE html>
<html>
<head>
<title>Underbound</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="game">
<script src="js/game.js"></script>
</div>
</body>
</html>
Because you're only checking if the hero collides with monster.
hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)
Instead, you should probably create a function for checking if they collide:
function isColliding(a, b) {
return a.x <= (b.x + 32) && b.x <= (a.x + 32) &&
a.y <= (b.y + 32) && b.y <= (a.y + 32);
}
if (isColliding(hero, monster)) { ...
Then use also check if they collide with crab.
if (isColliding(hero, crab)) { ...
It'd be more sustainable (until you have a whole lot of monsters) if you put all of your "monsters" into an array then check against each monster in the array.
As for the issue with gaining lots of points quickly: you have to remove the monster (or crab) from the play area and stop checking for collisions during the update phase or the player will continue to collide with the crab and gain points.
One solution for this would be to give your monsters an active (or similar property). By default, this will be true but when the player collides with them, this will be false. Then you will only draw them and check for collisions if active is true.
I saw many peps with same question but none of the solution helped me ..so i post the question.
I want to move my second pic "g_fighter.png" over the background . so i wrote the codes now its draw the images over the canvas but on keypress the pic dont move ! It will be very helpfull if anyone can find the flaw in my code
`
<html>
<body onload=start()>
<center>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">Your browser does not support canvas tag.</canvas>
</center>
<script>
//Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function(){
bgReady = true;
}
bgImage.src="img/heic0706a.jpg";
//Friend Image
var fReady = false;
var fImage = new Image();
fImage.onload = function(){
fReady = true;
}
fImage.src="img/g_fighter.png";
//Game objects
var hero = {
speed:1,
x:200,
y:390
};
var keysDown = {};
addEventListener("keydown", function(e){
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e){
delete keysDown[e.keyCode];
}, false);
function update(modifier){
if(38 in keysDown){
hero.y -= hero.speed * modifier;
}
if(40 in keysDown){
hero.y += hero.speed * modifier;
}
if(37 in keysDown){
hero.x -= hero.speed * modifier;
}
if(39 in keysDown){
hero.x += hero.speed * modifier;
}
}
function render(c){
if(bgReady == true){
c.drawImage(bgImage,0,0);
}
if(fReady == true){
c.drawImage(fImage,hero.x,hero.y,100,100);
}
}
function setImage(then){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var now = Date.now();
var delta = now-then;
update(delta/1000);
render(ctx);
then = now;
requestAnimationFrame(setImage);
}
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
function start(){
var Then = Date.now();
setImage(Then);
}
</script>
</body>
</html>
`
look a fiddle i set up:
http://jsfiddle.net/7fsw81mp/14/
function render(c){
c.clearRect(0,0,600,600)
if(fReady == true){
c.drawImage(fImage,hero.x,hero.y,100,100);
}
}
First of all I cannot see where were you calling the start function.
I put the then parameter as an external var, so i do not need to pass trought every requestAnimationFrame, i'm not sure if it goes as a parameter otherwise
Then the speed was very slow, 1 pixel per second, means that it barely moved
Also you have to clear the canvas every render, otherwise your hero will leave a trail behind him.
full snippet:
//Friend Image
var fReady = false;
var fImage = new Image();
fImage.onload = function(){
fReady = true;
}
fImage.src="http://vignette1.wikia.nocookie.net/finalfantasy/images/0/0a/FFTS_Fighter_Sprite.png";
var then = 0;
//Game objects
var hero = {
speed:10,
x:200,
y:390
};
var keysDown = {};
addEventListener("keydown", function(e){
keysDown[e.keyCode] = true;
e.preventDefault();
}, false);
addEventListener("keyup", function(e){
delete keysDown[e.keyCode];
e.preventDefault();
}, false);
function update(modifier){
if(38 in keysDown){
hero.y -= hero.speed * modifier;
}
if(40 in keysDown){
hero.y += hero.speed * modifier;
}
if(37 in keysDown){
hero.x -= hero.speed * modifier;
}
if(39 in keysDown){
hero.x += hero.speed * modifier;
}
}
function render(c){
c.clearRect(0,0,600,600)
if(fReady == true){
c.drawImage(fImage,hero.x,hero.y,100,100);
}
}
function setImage(){
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var now = Date.now();
var delta = now-then;
update(delta/1000);
render(ctx);
then = now;
requestAnimationFrame(setImage);
}
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
function start(){
console.log('starting');
then = Date.now();
setImage();
}
start();
<canvas id="myCanvas" width="600" height="600"></canvas>
During my summer vacation boredom took over, so I decided to start learning html5-games. In the process of making this very easy game somewhat better in functionality (logical, if you will) I ran into an issue I can't figure out myself. I hope you can guide me accordingly.
So I have race.html (which only has the Canvas to show to game in my webbrowser)
and I have game.js
It's a simply 2D car game. The car goes down a road and in order to not run out of fuel, it has to catch as many fuel-tanks as possible in order to win.
My problem lies in the process of getting the "fuel-tank-image" to render and reset only between the x and y coordinates of the 'road'. Currently it resets and renders all over te place but not specifically on the 'road' where the car is driving.
Here is my game.js code:
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 1024;
canvas.height = 768;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "img/map.png";
// car image
var carReady = false;
var carImage = new Image();
carImage.onload = function () {
carReady = true;
};
carImage.src = "img/car.png";
// fuel image
var fuelReady = false;
var fuelImage = new Image();
fuelImage.onload = function () {
fuelReady = true;
};
fuelImage.src = "img/fuel.jpg";
// Game objects
var car = {
speed: 500 // movement in pixels per second
};
var fuel = {};
var fuelsCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a fuel
var reset = function () {
car.x = canvas.width / 3;
car.y = canvas.height / 1.3;
// Throw the fuel somewhere on the screen randomly [lengte(math random) keer breedte voor een random plaat in de oppervlakte)]
fuel.x = 300 + (Math.random() * (canvas.width - 700));
fuel.y = 400 + (Math.random() * (canvas.height - 550));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
car.y -= car.speed * modifier;
}
if (40 in keysDown) { // Player holding down
car.y += car.speed * modifier;
}
if (37 in keysDown) { // Player holding left
car.x -= car.speed * modifier;
}
if (39 in keysDown) { // Player holding right
car.x += car.speed * modifier;
}
// Are they touching?
if (
car.x <= (fuel.x + 32)
&& fuel.x <= (car.x + 32)
&& car.y <= (fuel.y + 32)
&& fuel.y <= (car.y + 32)
) {
++fuelsCaught;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (carReady) {
ctx.drawImage(carImage, car.x, car.y);
}
if (fuelReady) {
ctx.drawImage(fuelImage, fuel.x, fuel.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "14px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Fuel Tanks caught: " + fuelsCaught + "/100", 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
// Request to do this again ASAP
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
var then = Date.now();
reset();
main();
the emphasis is on this piece:
// Throw the fuel somewhere on the screen randomly [lengte(math random) keer breedte voor een random plaat in de oppervlakte)]
fuel.x = 300 + (Math.random() * (canvas.width - 700));
fuel.y = 400 + (Math.random() * (canvas.height - 550));
I have altered the 300 and the 700 often in order to get a clear perspective on the correlation. But to no avail, because the reset is not logical.
this is the image of the road (which has a res of: 1024x768):
this is the car:
And this is the fuel-tank:
and the race.html code is this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Race</title>
</head>
<body>
<script src="js/game.js"></script>
</body>
</html>
The idea is to render/reset the fuel-tank between the road sides and just above the car.
This is fun. So let's say we start by defining the Y coordinate. Y can be between the top of the road and the bottom or the canvas (or 400 as you've given). Your code does this:
fuel.y = 400 + (Math.random() * (canvas.height - 550));
The road gets thinner and starts more towards the right towards the top, we need to define how this happens. Let's say that at the bottom of the screen it starts 10px to the right, and at the maximum y, y=1000px it starts 600px to the right. (I've made these numbers up obviously, you'll have to refine them to suit your case).
Let's also say that at the bottom of the screen the width is 600px and at the top it is 30px. We need to define two formulae to describe:
The left-most x coordinate for each y coordinate,
The road-width for each y coordinate.
Here:
var left_most_x = 10 + ((600-10)/1000) * fuel.y
var road_width = 600 - ((600-30)/1000) * fuel.y
Then you can define the x position as:
fuel.x = left_most_x + (Math.random() * road_width)
This is a game I am making. I cant figure out why it is not working. I have the JS fiddle here http://jsfiddle.net/aa68u/4/
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "http://6269-9001.zippykid.netdna-cdn.com/wp-content/uploads/2013/11/Woods-Wallpaper.jpg";
// Ship image
var shipReady = false;
var shipImage = new Image();
shipImage.onload = function () {
shipImage = true;
};
shipImage.src = "http://s29.postimg.org/3widtojzn/hero.png";
// Astroid image
var astroidReady = false;
var astroidImage = new Image();
astroidImage.onload = function () {
astroidReady = true;
};
astroidImage.src = "http://s29.postimg.org/4r4xfprub/monster.png";
// Game objects
var ship = {
speed: 256;
};
var astroid = {};
var health = 100;
window.keyStates = {};
addEventListener('keydown', function (e) {
keyStates[e.keyCode || e.key] = true;
e.preventDefault();
e.stopPropagation();
}, true);
addEventListener('keyup', function (e) {
keyStates[e.keyCode || e.key] = false;
e.preventDefault();
e.stopPropagation();
}, true);
var reset = function () {
astroid.width = 10;
astroid.height = 10;
astroid.x = 32 + (Math.random() * (canvas.width - 64));
astroid.y = 32 + (Math.random() * (canvas.height - 64));
ship.speed = 256;
for (var p in keyStates) keyStates[p]= false;
};
// Update game objects
function update (modifier) {
if (keyStates[38] ==true) { // Player holding up
astroid.x -= ship.speed * modifier;
}
if (keyStates[40]==true) { // Player holding down
astroid.x += ship.speed * modifier;
}
if (keyStates[37]==true) { // Player holding left
astroid.y -= ship.speed * modifier;
}
if (keyStates[39]==true) { // Player holding right
astroid.y += ship.speed * modifier;
}
if (astroid.width) < 200{
astroid.width +=10;
astroid.height += 10;
}
if (astroid.width) > 200{
reset();
}
// Are they touching?
if (keyStates[32] == true && ship.x <= (astroid.x + 32) && astroid.x <= (ship.x + 32) && ship.y <= (astroid.y + 32) && astroid.y <= (ship.y + 32)) {
monstersCaught += 1;
reset();
}
};
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (shipReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (astroidReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Your Health: " + health, 32, 32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
if (delta > 20) delta = 20;
update(delta / 1000);
render();
then = now;
};
// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
The game is supposed to be a ship(shoe image) that is avoiding astroids that get bigger(ants) but when you move your ship(shoe) stays in the same place and the astroids(ants) move. The ants/astroids also get bigger like you are going close to them.
var ship = {
speed: 256;
};
Remove the ; after the value.
if astroid.width < 200{
and
if astroid.width > 200{
Need parentheses around the if conditions.
The error console is helpful! But now it's just stuck in an infinite loop of monsterImage is not defined. Just... go back, write your code more carefully, and use the error console! It's there for a reason!
My HTML5 Canvas element doesn't seem to hide.
I created a timer that should hide the element when the timer reaches 0, I tested this with an alert flag and that worked fine.
Issue:
if (TotalSeconds <= 0)
{
ctx.clearRect(0, 0, canvas.width, canvas.height)
}
Entire code:
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
heroReady = true;
};
heroImage.src = "images/hero.png";
// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
monsterReady = true;
};
monsterImage.src = "images/flamingo.png";
// Game objects
var hero = {
speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function (e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function (e) {
delete keysDown[e.keyCode];
}, false);
// Reset the game when the player catches a monster
var reset = function () {
hero.x = canvas.width / 2;
hero.y = canvas.height / 2;
// Throw the monster somewhere on the screen randomly
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
};
// Update game objects
var update = function (modifier) {
if (38 in keysDown) { // Player holding up
hero.y -= hero.speed * modifier;
}
if (40 in keysDown) { // Player holding down
hero.y += hero.speed * modifier;
}
if (37 in keysDown) { // Player holding left
hero.x -= hero.speed * modifier;
}
if (39 in keysDown) { // Player holding right
hero.x += hero.speed * modifier;
}
// Are they touching?
if (
hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)
)
{
++monstersCaught;
reset();
}
if (hero.x <= 0)
{
hero.x = 510
}
if (hero.y <= 0)
{
hero.y = 478
}
};
CreateTimer(5);
var Timer;
var TotalSeconds;
function CreateTimer(Time) {
Timer = $("#timer").text();
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
$("#timer").text(TotalSeconds);
if (TotalSeconds <= 0)
{
ctx.clearRect(0, 0, canvas.width, canvas.height)
}
}
// Draw everything
var render = function () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (heroReady) {
ctx.drawImage(heroImage, hero.x, hero.y);
}
if (monsterReady) {
ctx.drawImage(monsterImage, monster.x, monster.y);
}
// Score
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Flamingos slaughtered: " + monstersCaught, 32, 32);
ctx.textAlign = "right";
ctx.textBaseline = "bottom";
ctx.fillText("Time left: " + TotalSeconds, 150,32);
};
// The main game loop
var main = function () {
var now = Date.now();
var delta = now - then;
update(delta / 1000);
render();
then = now;
};
// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
The html is just <canvas></canvas>
Pretty new to this so any help would be appreciated.
Thanks!
This does not hide the canvas but clear the context, which means it's clear the drawn shape on canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
You can hide it by appying a CSS style for it:
if (TotalSeconds <= 0) {
ctx.canvas.style.display = 'none';
}
and to reveal it again simple use block or inline-block instead of none.
If you want to hide it but keep its space you can use:
ctx.canvas.style.visibility = 'hidden';
You can also remove it completely from the DOM tree by using:
parent.removeChild(canvasElement);
where parent is the container element (for example document.body as you are using now) and canvasElement is a reference is your canvas.
All that being said - if you want to just clear the canvas then you need to stop the loop you have running. You can use for example a flag to do this:
function Tick() {
TotalSeconds--;
UpdateTimer();
if (TotalSeconds > 0) setTimeout(Tick, 1000); // only loop if sec > 0
}
and then clear it as you already do.
Hope this helps!