Uncaught ReferenceError: function not defined at onclick - javascript

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>

Related

CSS causes the canvas games buttons and on screen clicks to break. How do I fix it?

Why centering and even adding a header tag is causing the code's buttons to go off of the input area? I want to add some designs to the background but have no idea why the buttons are off of the input area. It is for a canvas game called bug smasher that needs mouse input.
Javascript:
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var timer = 0;
var caught = false;
var fps = 10;
document.body.appendChild(canvas);
canvas.width = 800;
canvas.height = 544;
// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.png";
// bug image
var bugReady = false;
var bugImage = new Image();
bugImage.onload = function () {
bugReady = true;
};
bugImage.src = "images/bug.png";
var bug = {};
var bugCaught = 0;
// When bug is caught, reset
var reset = function () {
bug.x = 40 + (Math.random() * (canvas.width - 70));
do {
bug.y = 40 + (Math.random() * (canvas.height - 70));
}
while (bug.y < 100)
};
//mousedown event
window.addEventListener("mousedown", onMouseDown, false);
function onMouseDown(e) {
if (e.button != 0) return;
mouseXinCanvas = e.clientX;
mouseYinCanvas = e.clientY;
if (bugBody(bug, mouseXinCanvas, mouseYinCanvas)) {
caught = true;
clearInterval(timer);
timer = setInterval(reset, 20000 / fps);
reset();
}
if (ResetScore(mouseXinCanvas, mouseYinCanvas)) {
location.reload();
}
if (ResetSpeed(mouseXinCanvas, mouseYinCanvas)) {
clearInterval(timer);
timer = setInterval(reset, 20000 / fps);
reset();
render();
}
};
//bug's body define
function bugBody(bug, x, y) {
if (x <= (bug.x + 80)
&& bug.x <= (x + 80)
&& y <= (bug.y + 80)
&& bug.y <= (y + 80)
) {
fps = fps + 5;
bugCaught++;
return true;
}
return false;
};
//Reset Score box
function ResetScore(x, y) {
if (x > (305)
&& x < (545)
&& y > (15)
&& y < (85)
) {
return true;
}
return false;
};
//Reset speed box
function ResetSpeed(x, y) {
if (x > (605)
&& x < (845)
&& y > (15)
&& y < (85)
) {
fps = 10;
return true;
}
return false;
};
// Draw everything
var render = function () {
//===========================================================
// add the following line to clear the display.
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
if (bgReady) {
ctx.drawImage(bgImage, 0, 100);
}
if (bugReady) {
ctx.drawImage(bugImage, bug.x, bug.y);
}
if (caught == true) {
if (bgReady) {
ctx.drawImage(bgImage, 0, 100);
}
caught = false;
}
// Score, Title
ctx.fillStyle = "rgb(65, 226, 24)";
ctx.font = "34px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Bug Smasher", 5, 40);
ctx.font = "20px Helvetica";
ctx.fillText("Score: " + bugCaught, 10, 10);
// Reset Score, Speed button
ctx.fillStyle = "rgb(30, 168, 99)";
ctx.fillRect(250, 10, 250, 80);
ctx.fillRect(520, 10, 250, 80);
ctx.fillStyle = "rgb(30, 168, 99)";
ctx.fillRect(255, 15, 240, 70);
ctx.fillRect(525, 15, 240, 70);
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.font = "34px Arial";
ctx.fillText("Reset Score", 275, 30);
ctx.fillText("Reset Speed", 545, 30);
};
// The main game loop
var main = function () {
render();
// 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();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content = "width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="Assignment5.css">
<title>Assignment 5</title>
</head>
<body>
<main>
<script src="Assignment5.js"></script>
</main>
</body>
</html>
When you add other elements to your code your <canvas> element will shift accordingly. What you are not accounting for in your mouse function is the canvas position in relation to the window.
I'm sure you've noticed that when you add elements the canvas moves down but the collision for the button and the bug do not move in relation to the canvas. So in your mouse function you need to subtract the canvas x and y position
window.addEventListener("mousedown", onMouseDown, false);
function onMouseDown(e) {
let canvasBounds = canvas.getBoundingClientRect(); //add this
if (e.button != 0) return;
mouseXinCanvas = e.clientX - canvasBounds.x; //can also be canvasBounds.left
mouseYinCanvas = e.clientY - canvasBounds.y; //can also be canvasBoudns.top
if (bugBody(bug, mouseXinCanvas, mouseYinCanvas)) {...

Flickering images with Javascript

I am trying to make a game in Javascript with Repl.it, but every few seconds the player's images flickers. I cannot figure out why this is happening? I am loading some images onto a canvas and it only started flickering once I added in the animate() function and started changing the image. Can someone please explain this? (go to this website to see the flicker and play the game too: https://advanced-chrome-dino-game.isaacroot.repl.co/) My code:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var ground_size = 75;
var up = false;
var game_over = false;
const start_speed = 8;
var score = 0;
function randBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
class Player {
constructor(x_pos) {
this.color = "black";
this.image = "dino_1.png"
this.img = new Image();
this.width = 120;
this.height = 120;
this.x = x_pos;
this.y = c.height - ground_size - this.height;
this.speed = 0;
this.jump_power = 22.5;
this._gravity = 1;
this.an_time = 7;
this.an_count = 0;
}
ground_height() {
return c.height - ground_size - this.height;
}
on_ground() {
if (this.y == this.ground_height()) {
return true;
} else {
return false;
}
}
jump() {
if (this.on_ground()) {
this.speed = this.jump_power;
this.image = "dino_jump.png";
}
}
gravity() {
this.speed -= this._gravity;
}
animate() {
if (this.an_count <= 0) {
if (this.image == "dino_1.png") {
this.image = "dino_2.png";
} else {
if (this.image == "dino_2.png") {
this.image = "dino_1.png"
}
}
this.an_count = this.an_time;
} else {
this.an_count -= 1;
}
}
react() {
this.y -= this.speed
if (this.y > this.ground_height()) {
this.y = this.ground_height();
this.speed = 0;
}
if (this.on_ground() && this.image == "dino_jump.png") {
this.image = "dino_1.png"
}
}
rect() {
return [this.x, this.y, this.width, this.height]
}
}
class Obstacle {
constructor(x_pos, speed) {
this.color = "red";
this.img = new Image();
this.img.src = "cactus_big.png";
this.width = 52 * 1.5;
this.height = 75 * 1.5;
this.x = x_pos;
this.y = c.height - ground_size - this.height;
this.speed = speed;
}
ground_height() {
return c.height - ground_size - this.height;
}
on_ground() {
if (this.y == this.ground_height()) {
return true;
} else {
return false;
}
}
react() {
if (this.x <= 0 - this.width) {
this.x = randBetween(c.width, c.width + 500);
}
this.x -= this.speed;
}
rect() {
return [this.x, this.y, this.width, this.height]
}
}
player = new Player(75);
obstacle1 = new Obstacle(c.width, start_speed);
function inRect(rect1, rect2) {
var rect1_left = rect1[0];
var rect1_right = rect1[0] + rect1[2];
var rect1_top = rect1[1];
var rect1_bottom = rect1[1] + rect1[3];
var rect2_left = rect2[0];
var rect2_right = rect2[0] + rect2[2];
var rect2_top = rect2[1];
var rect2_bottom = rect2[1] + rect2[3];
var horizontal = false;
var vertical = false;
if (rect1_right > rect2_left && rect2_right > rect1_left) {
horizontal = true;
}
if (rect1_bottom > rect2_top && rect2_bottom > rect1_top) {
vertical = true;
}
return (vertical && horizontal);
}
function draw() {
ctx.beginPath();
ctx.fillStyle = "white";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "#4b4b4b";
ctx.fillRect(0, c.height - ground_size, c.width, c.height);
ctx.fillStyle = player.color;
// ctx.fillRect(player.x, player.y, player.width, player.height);
player.img.src = player.image;
ctx.drawImage(player.img, player.x, player.y, player.width, player.height)
ctx.fillStyle = obstacle1.color;
// ctx.fillRect(obstacle1.x, obstacle1.y, obstacle1.width, obstacle1.height);
ctx.drawImage(obstacle1.img, obstacle1.x, obstacle1.y, obstacle1.width, obstacle1.height)
ctx.fillStyle = "black";
ctx.font = "30px Arial";
ctx.fillText("Score: " + Math.round(score / 25).toString(), 20, 50);
if (game_over) {
ctx.font = "80px Arial";
}
ctx.stroke();
}
document.addEventListener('keydown', (event) => {
if (event.key == 'ArrowUp' || event.key == 'Spacebar') {
up = true;
} else if (event.key == 'ArrowDown') {
//pass
}
});
document.addEventListener('keyup', (eventt) => {
if (eventt.key == 'ArrowUp') {
up = false;
} else if (event.key == 'ArrowDown') {
//pass
}
});
function update_speed() {
obstacle1.speed += 0.001;
}
function run() {
if (up == true) {
player.jump()
}
player.gravity();
player.react();
player.animate();
obstacle1.react();
if (inRect(player.rect(), obstacle1.rect())) {
game_over = true
}
score += obstacle1.speed
draw();
update_speed();
if (game_over == false) {
requestAnimationFrame(run);
}
}
run();
I checked the code and I realized you were loading images each time into the player.img variable.
function createImage(path){
let image = new Image();
image.src = path;
return image;
}
var images = {
dino:[
createImage("dino_1.png"),
createImage("dino_2.png"),
createImage("dino_jump.png")
],
cactus:createImage("cactus_big.png")
}
If you use my code here, you need to change the code to use those images instead. Because now, each time you draw, you are loading an image. Like this, all images are stored and I tried it, no more flickering.
Well, all you have to do is have the images get preloaded so your index.html should look like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Block Runner</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="preload" href="cactus_big.png" as="image">
<link rel="preload" href="dino_1.png" as="image">
<link rel="preload" href="dino_2.png" as="image">
<link rel="preload" href="dino_jump.png" as="image">
<link rel="preload" href="ground.png" as="image">
</head>
<body>
<canvas id="myCanvas" width="900" height="600" style="border:0px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script src="script.js"></script>
</body>
</html>
That should make it so that it doesn't flicker.

Placing an object from an array in a canvas

I'm making a game for school and wanted to place some trees in it. I thought it would be nice if i could make an array and place several trees from the array in the canvas. it seems that the array doesn't draw the trees on the canvas. I'm looking at it for hours and can't figure it out. Could somebody help me, please?
i've got two different .js documents. one is the general file and one for the trees.
First the general:
$(document).ready(function() {
var horse = new Image();
horse.src = "ash.png"
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var xPos = 0;
var yPos = 0;
var animStep = 0;
var sx = 0;
var sy = 96;
var previousStep = Date.now();
var moveRight = false;
var moveLeft = false;
var moveUp = false;
var moveDown = false;
var achtergrond = 0;
//background 1
var grass = new Image();
grass.src = "grass.png";
var grassPattern;
grass.onload = function(){
grassPattern = context.createPattern(grass,"repeat");
}
//background 2
var cave = new Image();
cave.src = "cave.png";
var cavePattern;
cave.onload = function(){
cavePattern = context.createPattern(cave,"repeat");
}
//start drawfunction --------------------------------------------
function draw(){
//make an array:
var objects = [];
//make the chests:
objects.push( new Chest(100,200) );
objects.push( new Chest(200,200) );
objects.push( new Chest(200,100) );
for (var i = 0; i < objects.length; i++) {
objects[i].draw();
}
update();
spritesheet();
//spritesheet back in the canvas:
if ( xPos > canvas.width ) {
xPos = 0;
achtergrond = 1;
}
if (xPos < -32){
xPos = canvas.width;
achtergrond = 0;
}
if ( yPos > canvas.height ) {
// put the y to 0
yPos = 0;
achtergrond = 1;
}
if ( yPos < -32 ) {
yPos = canvas.height;
achtergrond = 0;
}
if (achtergrond == 0){
context.fillStyle=grassPattern;
context.fillRect (0,0,canvas.width,canvas.height);
}
else if (achtergrond == 1){
context.fillStyle=cavePattern;
context.fillRect (0,0,canvas.width,canvas.height);
}
context.drawImage(horse,animStep*32,sy,28,32,xPos,yPos,30,32);
// call the function walk:
walk();
requestAnimationFrame(draw);
}
draw();
//end draw function ----------------------------------------------------
$(document).keydown( function(evt) {
if (evt.which == 39){ // if the right arrow key is pressed
moveRight = true;
}
if (evt.which == 37){ // if the left arrow key is pressed
moveLeft = true;
}
if (evt.which == 38){ // if the up arrow key is pressed
moveUp = true;
}
if (evt.which == 40){ // if the down arrow key is pressed
moveDown = true;
}
});
$(document).keyup( function(evt) {
if (evt.which == 39){ // if the right arrow key is lifted
moveRight = false;
}
if (evt.which == 37){ // if the left arrow key is lifted
moveLeft = false;
}
if (evt.which == 38){ // if the up arrow key is lifted
moveUp = false;
}
if (evt.which == 40){ // if the down arrow key is lifted
moveDown = false;
}
});
function update() {
if (moveRight) {
xPos += 4;
} else if (moveLeft) {
xPos -= 4;
} else if (moveUp) {
yPos -= 4;
} else if (moveDown) {
yPos += 4;
}
}
function walk(){
if (Date.now() - previousStep > 1000/10) {
animStep += 1;
if (animStep == 5) {
animStep = 0;
}
previousStep = Date.now();
}
}
function spritesheet() {
if (moveUp) {
sy = 65;
} else if (moveDown) {
sy = 0;
} else if (moveRight){
sy = 96;
} else if (moveLeft) {
sy = 32;
}
// als we in geen enkele richting lopen (! betekent niet)
if (!moveRight && !moveLeft && !moveUp && !moveDown) {
// staan we blijkbaar stil en gebruiken we de neutrale pose
sx = animStep = 0;
} else {
// anders het huidige stapje maal de breedte van 1 stapje
sx = animStep * 32;
}
}
});
and the second .js file:
function Chest(x,y) {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
// Chest Image object maken
var img = new Image();
img.src = "boom.png";
this.draw = function() {
context.drawImage(img,0,0,33,33,this.x,this.y,33,33);
}
}
and ofcourse there is the canvas HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="rAF.js"></script>
<script src="objects.js"></script>
<script src="index.js"></script>
<title>Untitled Document</title>
</head>
<body>
<canvas id="myCanvas" width="600" height="400"></canvas>
</body>
</html>
Inside your Chest-function, declare the img.variable as local:
function Chest(x,y) {
//The function should be able to find these global variables without you delcaring them inside
//var canvas = document.getElementById('myCanvas');
//var context = canvas.getContext('2d');
//declaring your x and y variables
this.x = x;
this.y = y;
// Chest Image object maken
this.img = new Image();
this.img.src = "boom.png";
this.draw = function() {
context.drawImage(this.img,0,0,33,33,this.x,this.y,33,33);
}
}

What is the benefit of requestAnimationFrame(...paramList...)?

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".

Javascript Html5 canvas problems

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!

Categories