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>
Related
I'm receiving an 'Uncaught Reference Error: function(e.g upButton()) is not defined at HTMLButtonElement.onclick'. I have a simple canvas game from a tutorial I followed which uses keyboard controls to move, however I wanted buttons too.
I always do a test page to make sure that everything's working fine, which it did, before I move it all to my main html file, however although I have literally copied and pasted my code from one file to the other it's giving me this error.
The html button code:
<button onclick="upButton()">Up</button>
<button onclick="downButton()">Down</button>
<button onclick="leftButton()">Left</button>
<button onclick="rightButton()">Right</button>
My javascript function code:
function upButton() {
character.y -= 15;
}
function downButton() {
character.y += 15;
}
function leftButton() {
character.x -= 15;
}
function rightButton() {
character.x += 15;
}
From the fact that my test html file works, I thought that everything was defined correctly, and that it was calling this function correctly too, so I am unaware on why this is happening.
Full html code:
<!DOCTYPE html>
<html>
<head>
<title>CS25320</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<!-- Image from https://matthewboyz.deviantart.com/art/Blue-flat-wallpaper-555483912 -->
<body background="background.png">
<div id="header">
<h1>Mystical Mountains Game</h1>
<p>CS25320 / Programming for the Web</p>
<ul>
<li><b>Home</b></li>
<li><b>About</b></li>
<li><b>Help</b></li>
</ul>
</div>
<div id="main">
<br>
</div>
<p id="health"></p>
<p id="health2"></p>
<p id="health3"></p>
<p id="health4"></p>
<button onclick="upButton()">Up</button>
<button onclick="downButton()">Down</button>
<button onclick="leftButton()">Left</button>
<button onclick="rightButton()">Right</button>
<script src="thegame.js"></script>
<div id="footer">
<h3>Disclaimer</h3>
</div>
</body>
</html>
Full js code:
//Create Canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 450;
document.body.appendChild(canvas);
//Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function() {
bgReady = true;
};
bgImage.src = "background4.png";
//Character image
var charReady = false;
var charImage = new Image();
charImage.onload = function() {
charReady = true;
};
charImage.src = "character2.png";
//Jewel image
var jewelReady = false;
var jewelImage = new Image();
jewelImage.onload = function() {
jewelReady = true;
};
jewelImage.src = "jewel.png";
//Game objects
var character = {
speed: 256, // movement in pixels per second
x: 0,
y: 0
};
var jewel = { // Doesn't move so just has coordinates
x: 0,
y: 0
};
var jewelsCaught = 0; // Stores number of jewel caught
// Handle keyboard controls
var keysDown = {};
addEventListener("keydown", function(e) {
keysDown[e.keyCode] = true;
}, false);
addEventListener("keyup", function(e) {
delete keysDown[e.keyCode];
}, false);
//Buttons for cross-compatibility with other devices
//I have added in this code to allow the user to use buttons
function upButton() {
character.y -= 15;
}
function downButton() {
character.y += 15;
}
function leftButton() {
character.x -= 15;
}
function rightButton() {
character.x += 15;
}
//Reset the game when the character catches a troll or jewel
var reset = function() {
character.x = canvas.width / 2;
character.y = canvas.height / 2;
//Throw jewel on screen randomly
jewel.x = 32 + (Math.random() * (canvas.width - 64));
jewel.y = 32 + (Math.random() * (canvas.height - 64));
};
//Update game objects
var update = function(modifier) {
if (38 in keysDown) { // Player holding up
character.y -= character.speed * modifier;
}
if (40 in keysDown) { // Player holding down
character.y += character.speed * modifier;
}
if (37 in keysDown) { // Player holding left
character.x -= character.speed * modifier;
}
if (39 in keysDown) { // Player holding right
character.x += character.speed * modifier;
}
//Are they touching?
if (
character.x <= (jewel.x + 52)
&& jewel.x <= (character.x + 52)
&& character.y <= (jewel.y + 52)
&& jewel.y <= (character.y + 52)
) {
++jewelsCaught;
reset();
}
};
//Draw everything
var render = function() {
if (bgReady) {
ctx.drawImage(bgImage, 0, 0);
}
if (charReady) {
ctx.drawImage(charImage, character.x, character.y);
}
if (jewelReady) {
ctx.drawImage(jewelImage, jewel.x, jewel.y);
}
//Score
ctx.fillStyle = "rgb(0,0,0)";
ctx.font = "20px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Jewels caught: " + jewelsCaught, 32, 32);
};
var i = 0;
for (i = 0; i < 100; i++) {
if (jewelsCaught <= 5) {
document.getElementById("health").innerHTML = "Health: *";
}
else if (jewelsCaught >= 6) {
document.getElementById("health2").innerHTML = "Health: **";
}
else if (jewelsCaught >= 11 && jewelsCaught <= 15) {
document.getElementById("health3").innerHTML = "Health: ***";
}
else if (jewelsCaught >= 16 && jewelsCaught <= 20) {
document.getElementById("health4").innerHTML = "Health: ****";
}
}
//Main game loop
var main = function() {
var now = Date.now();
//How many milliseconds have passed since the last interval
var delta = now - then;
update(delta / 1000);
//Record the timestamp
render();
then = now;
//Request to do this again ASAP
requestAnimationFrame(main);
};
//Cross-brower support for requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
//Play game
var then = Date.now();
reset();
main();
You should be aware that the code is already included to the page. For you full html code, I cannot find your javascript function code, upButton, downButton, leftButton and rightButton. It is no problem for the following code snippet.
//file: thegame.js
//Create Canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 450;
document.body.appendChild(canvas);
//Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function() {
bgReady = true;
};
bgImage.src = "background4.png";
//Character image
var charReady = false;
var charImage = new Image();
charImage.onload = function() {
charReady = true;
};
charImage.src = "character2.png";
//Jewel image
var jewelReady = false;
var jewelImage = new Image();
jewelImage.onload = function() {
jewelReady = true;
};
jewelImage.src = "jewel.png";
//Game objects
var character = {
speed: 256, // movement in pixels per second
x: 0,
y: 0
};
function upButton() {
character.y -= 15;
}
function downButton() {
character.y += 15;
}
function leftButton() {
character.x -= 15;
}
function rightButton() {
character.x += 15;
}
<!DOCTYPE html>
<html>
<head>
<title>CS25320</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<!-- Image from https://matthewboyz.deviantart.com/art/Blue-flat-wallpaper-555483912 -->
<body background="background.png">
<div id="header">
<h1>Mystical Mountains Game</h1>
<p>CS25320 / Programming for the Web</p>
<ul>
<li><b>Home</b></li>
<li><b>About</b></li>
<li><b>Help</b></li>
</ul>
</div>
<div id="main">
<br>
</div>
<p id="health"></p>
<p id="health2"></p>
<p id="health3"></p>
<p id="health4"></p>
<button onclick="upButton()">Up</button>
<button onclick="downButton()">Down</button>
<button onclick="leftButton()">Left</button>
<button onclick="rightButton()">Right</button>
<!-- include in code snippet -->
<!-- <script src="thegame.js"></script> -->
<div id="footer">
<h3>Disclaimer</h3>
</div>
</body>
</html>
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.
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".
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!