Using Javascript to create HTML5 Canvas Game - Bug Smasher - javascript

I'm trying to use Javascript to create a Canvas Game which is similar to Bug Smasher or Ant Smasher game. It means the obj will move randomly, and when u click on it, the score will increase. ( I'm not allowed to use JQuery )
I almost finished all the work. But there's an error I cannot figure out: Everytime I click on the object, the score increases but it overwrites the number "0" like this:
And this is my code:
// 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";
// nar image
var narReady = false;
var narImage = new Image();
narImage.onload = function () {
narReady = true;
};
narImage.src = "images/nar.png";
var nar = {};
var narCaught = 0;
// When nar is caught, reset
var reset = function () {
nar.x = 40 + (Math.random() * (canvas.width - 70));
do {
nar.y = 40 + (Math.random() * (canvas.height - 70));
}
while (nar.y < 100)
};
//mousedown event
window.addEventListener("mousedown", onMouseDown, false);
function onMouseDown(e) {
if (e.button != 0) return;
mouseXinCanvas = e.clientX;
mouseYinCanvas = e.clientY;
if (narBody(nar, 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();
}
};
//nar's body define
function narBody(nar, x, y) {
if (x <= (nar.x + 80)
&& nar.x <= (x + 80)
&& y <= (nar.y + 80)
&& nar.y <= (y + 80)
) {
fps = fps + 5;
narCaught++;
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 () {
if (bgReady) {
ctx.drawImage(bgImage, 0, 100);
}
if (narReady) {
ctx.drawImage(narImage, nar.x, nar.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("Catch Naruto!!!", 5, 40);
ctx.font = "20px Helvetica";
ctx.fillText("Score: " + narCaught, 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 lang="en">
<head>
<meta charset="utf-8">
<title>Assignment 5</title>
</head>
<body>
<script src="game.js"></script>
</body>
</html>
Please help ! :(

The problem is simple to solve. You just need to clear all the previous frame's rendering before you render the new frame.
Just add the following line to the render function
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
You will notice that the quality of the text also improves. This is because you are no long drawing over the top of the old text,
I dont know what the background image is so I clear the whole canvas. But if the background image is not transparent you only need to clear what it does not cover.
See change below
// 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";
// nar image
var narReady = false;
var narImage = new Image();
narImage.onload = function () {
narReady = true;
};
narImage.src = "images/nar.png";
var nar = {};
var narCaught = 0;
// When nar is caught, reset
var reset = function () {
nar.x = 40 + (Math.random() * (canvas.width - 70));
do {
nar.y = 40 + (Math.random() * (canvas.height - 70));
}
while (nar.y < 100)
};
//mousedown event
window.addEventListener("mousedown", onMouseDown, false);
function onMouseDown(e) {
if (e.button != 0) return;
mouseXinCanvas = e.clientX;
mouseYinCanvas = e.clientY;
if (narBody(nar, 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();
}
};
//nar's body define
function narBody(nar, x, y) {
if (x <= (nar.x + 80)
&& nar.x <= (x + 80)
&& y <= (nar.y + 80)
&& nar.y <= (y + 80)
) {
fps = fps + 5;
narCaught++;
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 (narReady) {
ctx.drawImage(narImage, nar.x, nar.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("Catch Naruto!!!", 5, 40);
ctx.font = "20px Helvetica";
ctx.fillText("Score: " + narCaught, 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();

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)) {...

HTML5 Javascript Object Has Been Clicked On

I'm making a game where your mouse is a cross hair and you click on zombies moving across the screen. I'm having troubles figuring out how to find if the mouse has clicked on a zombie. The zombies are made in JavaScript so I can't use the onclick attribute in HTML. This is my code.
var mouseX;
var mouseY;
$(document).ready(function(){
var canvasWidth = 640;
var canvasHeight = 480;
var canvas = $("#gameCanvas")[0];
var context = canvas.getContext("2d");
var score = 0;
var timer = 0;
var spawnZombie = false;
//crosshair
var crossHair = new Image();
var crosshairX = 50;
var crosshairY = 50;
crossHair.src = "media/crosshair.png";
//zombies
var zombies = [];
var zombieLeft = new Image();
zombieLeft.src = "media/zombieLEFT.gif";
var zombieRight = new Image();
zombieRight.src = "media/zombieRIGHT.gif";
var fps = 30;
setInterval(function(){
update();
draw();
}, 1000/fps);
function update(){
timer += 1;
crosshairX = mouseX - 445;
crosshairY = mouseY - 125;
if(timer >= 70){
timer = 0;
spawnZombie = true;
}
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
zombies = zombies.filter(function(zombie){
return zombie.active;
});
if(spawnZombie){
zombies.push(Zombie(null, "left"));
zombies.push(Zombie(null, "right"));
spawnZombie = false;
}
}
function draw(){
context.clearRect(0,0, canvasWidth, canvasHeight);
context.fillStyle = "#000";
context.font = "20px Comic Sans MS";
context.fillText("Score: " + score, 50, 50);
zombies.forEach(function(zombie) {
zombie.draw();
});
context.drawImage(crossHair, crosshairX, crosshairY, 100, 100);
}
function Zombie(I, dir){
I = I || {};
I.active = true;
I.speed = 5;
I.y = getRandomInt(50, 350);
if(dir == "left"){
I.x = 800;
}
else if(dir == "right"){
I.x = -100;
}
I.width = 100;
I.height = 100;
I.inBounds = function() {
return I.x >= 0 && I.x <= canvasWidth &&
I.y >= 0 && I.y <= canvasHeight;
};
I.draw = function(){
if(dir == "left"){
context.drawImage(zombieLeft, this.x, this.y, this.width, this.height);
}
else if(dir == "right"){
context.drawImage(zombieRight, this.x, this.y, this.width, this.height);
}
};
I.update = function(){
if(dir == "left"){
this.x -= this.speed;
}
else if(dir == "right"){
this.x += this.speed;
}
};
I.onclick = function(){
I.remove();
};
return I;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
});
$( document ).on( "mousemove", function( event ) {
mouseX = event.pageX;
mouseY = event.pageY;
});
This is the specific spot where I'm trying to detect if the zombie has been clicked on within my update functio
zombies.forEach(function(zombie) {
zombie.update();
document.body.onmousedown = function() {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
//if(mouseX)
};
});
I can't use the onclick attribute in HTML.
But you can use the addEventListener method in your javascript:
eg.
zombieLeft.addEventListener('click', myFunction, false);
document.body.onmousedown = function(event) {
console.log(zombie.x.toString() + ", " + zombie.y.toString());
if(event.pageX == zombie.x && event.pageY == zombie.y){
//Zombie clicked
}
};
This is pseudo code. You can attach event and you can check for x and y.

Why does the drawDashedLine function mess up my game?

I found a pong game online and wanted to change it around a bit. I want to put a dashed line in the middle of the screen.
if I take out the dashed line the game works. It will work in Chrome but locks up on the Firefox OS simulator.
****Question: Why would this be the case?"****
Code:
function drawDashedLine() {
ctx.beginPath();
ctx.fillStyle = '#eee';
ctx.setLineDash([1,2]);
ctx.moveTo(0,H/2);
ctx.lineTo(320,H/2);
ctx.closePath();
ctx.stroke();
}
HTML:
<html>
<head>
<title>Firefox OS</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();
//all global variables
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d"); // Create canvas context
//W = window.innerWidth, // Window's width
//H = window.innerHeight, // Window's height
var W = 310;
var H = 440;
var particles = []; // Array containing particles
var ball = {}; // Ball object
var paddles = [2]; // Array containing two paddles
var mouse = {}; // Mouse object to store it's current position
var points = 0; // Varialbe to store points
var fps = 60; // Max FPS (frames per second)
var flag = 0; // Flag variable which is changed on collision
var particlePos = {}; // Object to contain the position of collision
var multipler = 1; // Varialbe to control the direction of sparks
var startBtn = {}; // Start button object
var restartBtn = {}; // Restart button object
var over = 0; // flag varialbe, cahnged when the game is over
var init; // variable to initialize animation
var paddleHit;
// Add mousemove and mousedown events to the canvas
canvas.addEventListener("mousemove", trackPosition, true);
canvas.addEventListener("mousedown", btnClick, true);
// Set the canvas's height and width to full screen
canvas.width = W;
canvas.height = H;
// Ball object
ball = {
x: 50,
y: 50,
r: 5,
c: "red",
vx: 3,
vy: 7,
// Function for drawing ball on canvas
draw: function() {
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
ctx.fill();
}
};
// Start Button object
startBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 25,
draw: function() {
ctx.strokeStyle = "white";
ctx.lineWidth = "2";
ctx.strokeRect(this.x, this.y, this.w, this.h);
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStlye = "white";
ctx.fillText("Start", W/2, H/2 );
}
};
// Restart Button object
restartBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 50,
draw: function() {
ctx.strokeStyle = "white";
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Tap Center Screen To Play Again!", W/2, H/2 - 25 );
}
};
// Function to paint canvas
function paintCanvas() {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 310, 440);
}
// Function for creating paddles
function Paddle(pos) {
// Height and width
this.h = 8;
this.w = 55;
// Paddle's position
this.x = W/2 - this.w/2;
this.y = (pos == "top") ? 0 : H - this.h;
}
function draw() {
paintCanvas();
for(var i = 0; i < paddles.length; i++) {
p = paddles[i];
ctx.fillStyle = "white";
ctx.fillRect(p.x, p.y, p.w, p.h);
}
ball.draw();
update();
}
function increaseSpd() {
if(points % 2 == 33) {
if(Math.abs(ball.vx) < 15) {
ball.vx += (ball.vx < 0) ? -1 : 1;
ball.vy += (ball.vy < 0) ? -2 : 2;
}
}
}
function trackPosition(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function movePaddles() {
if(mouse.x && mouse.y) {
for(var i = 1; i < paddles.length; i++) {
p = paddles[i];
p.x = mouse.x - p.w/2;
}
}
}
function collisions() {
if(collides(ball, p1)) {
collideAction(ball, p1);
}
else if(collides(ball, p2)) {
collideAction(ball, p2);
} else {
// Collide with walls, If the ball hits the top/bottom,
// walls, run gameOver() function
if(ball.y + ball.r > H) {
ball.y = H - ball.r;
gameOver(); //the game is over
} else if(ball.y < 0) {
ball.y = ball.r;
gameOver(); //the game is over
}
if(ball.x + ball.r > W) {
ball.vx = -ball.vx;
ball.x = W - ball.r;
} else if(ball.x -ball.r < 0) {
ball.vx = -ball.vx;
ball.x = ball.r;
}
}
}
function drawDashedLine() {
ctx.beginPath();
ctx.fillStyle = '#eee';
ctx.setLineDash([1,2]);
ctx.moveTo(0,H/2);
ctx.lineTo(320,H/2);
ctx.closePath();
ctx.stroke();
}
function update() {
updateScore();
movePaddles();
drawDashedLine()
ball.x += ball.vx;
ball.y += ball.vy;
p1 = paddles[1];
p2 = paddles[2];
collisions();
flag = 0;
}
function collides(b, p) {
if(b.x + ball.r >= p.x &&
b.x - ball.r <=p.x + p.w) {
if(b.y >= (p.y - p.h) && p.y > 0){
paddleHit = 1;
return true;
} else if(b.y <= p.h && p.y == 0) {
paddleHit = 2;
return true;
} else {
return false;
}
}
}
function collideAction(ball, p) {
ball.vy = -ball.vy;
if(paddleHit == 1) {
ball.y = p.y - p.h;
particlePos.y = ball.y + ball.r;
multiplier = -1;
} else if(paddleHit == 2) {
ball.y = p.h + ball.r;
particlePos.y = ball.y - ball.r;
multiplier = 1;
}
points++;
if(collision) {
if(points > 0) {
collision.pause();
}
collision.currentTime = 0;
collision.play();
}
particlePos.x = ball.x;
flag = 1;
}
// Function for updating score
function updateScore() {
ctx.fillStlye = "green";
ctx.font = "20px Arial, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(points, 20, 20 );
}
// Function to run when the game overs
function gameOver() {
ctx.fillStlye = "white";
ctx.font = "20px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Game Over! ("+points+")", W/2, H/2 + 25 );
cancelRequestAnimFrame(init); //stops the animation frame
over = 1;
restartBtn.draw(); //This will allow the user to restart the game
}
// Function for running the whole animation
function animloop() {
init = requestAnimFrame(animloop);
draw();
}
// Function to execute at startup
function startScreen() {
draw();
startBtn.draw();
}
// On button click (Restart and start)
function btnClick(e) {
var mx = e.pageX;
var my = e.pageY;
if(mx >= startBtn.x && mx <= startBtn.x + startBtn.w) {
animloop();
startBtn = {};
}
// If the game is over, and the restart button is clicked
if(over == 1) {
if(mx >= restartBtn.x && mx <= restartBtn.x + restartBtn.w) {
ball.x = 20;
ball.y = 20;
points = 0;
ball.vx = 4;
ball.vy = 8;
animloop();
over = 0;
}
}
}
paddles.push(new Paddle("bottom"));
paddles.push(new Paddle("top"));
startScreen();
</script>
</body>
</html>

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!

Canvas wont hide?

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!

Categories