Game with moving circle through obstacle in Javascript doesn't work - javascript

I created a game using Javascript. It is a game where a circle which can be controlled by the mouse, has to navigate through moving obstacles similar to a maze. When the circle hits an obstacle, the game should stop.
When i tried the same game but with one obstacle, it worked. But after adding more lines of code to create more obstacles, the circle and the obstacle doesn't appear in the output. Also, the crashWith function isn't being called when the circle hits the obstacle.
Here is the code:
<!DOCTYPE html>
<html>
<style>
canvas {
border:1px solid #000000;
background-image: url("https://data.whicdn.com/images/223851992/large.jpg");
}
</style>
<body onload="begin()">
<script>
var gamePiece;
var gameObstacle = [];
function begin(){
gameArea.start();
gamePiece = new piece(10, "white", 20, 135);
}
var gameArea = {
canvas : document.createElement("canvas"),
start : function(){
this.canvas.width = 480;
this.canvas.height = 270;
this.canvas.style.cursor= 'none';
this.context = this.canvas.getContext("2d");
document.body.insertBefore( this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGame , 10); //for each frame
window.addEventListener('mousemove', function(n){
gameArea.x = n.pageX;
gameArea.y = n.pageY;
});
},
clear : function(){
this.context.clearRect(0,0, this.canvas.width, this.canvas.height);
},
stop : function(){
clearInterval(this.interval);
}
}
function eachInterval(e){
if((gameArea.frameNo / e) % 1 == 0)
return true;
else
return false;
}
//for circle
function piece (radius, color, x, y){
this.radius = radius;
this.speedx = 0;
this.speedy =0;
this.x = x;
this.y = y;
this.update = function(){
pieceContext = gameArea.context;
pieceContext.beginPath();
pieceContext.arc( this.x, this.y, this.radius, 0, 2 * Math.PI);
pieceContext.fillStyle = color;
pieceContext.fill();
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
//for obstacle
function obstacle (width, height, color, x, y){
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy =0;
this.x = x;
this.y = y;
this.update = function(){
obstacleContext = gameArea.context;
obstacleContext.fillStyle = color;
obstacleContext.fillRect(this.x, this.y, this.width, this.height);
}
this.newPlace = function(){
this.x += this.speedx;
this.y += this.speedy;
}
//check crash
this.crashWith = function(gamePiece){
var collide = true;
var otherleft = this.x;
var otherright = this.x + (this.width);
var othertop = this.y;
var otherbottom = this.y + (this.height);
var circleBottom = gamePiece.y + (gamePiece.radius);
var circleTop = gamePiece.y;
var circleLeft = gamePiece.x;
var circleRight = gamePiece.x + (gamePiece.radius);
if ((circleBottom < othertop) || (circleTop > otherbottom) || (circleRight < otherleft) || (circleLeft > otherright)) {
collide = false;
}
return collide;
}
}
function updateGame(){
var x,y;
for(i=0 ; i<gameObstacle.length ; i++){
if (gameObstacle[i].crashWith(gamePiece)){
gameArea.stop();
return;
}
}
gameArea.clear();
gameArea.frameNo +=1 ;
if(gameArea.frameNo == 1 || eachInterval(150)){
x = gameArea.canvas.width;
y = gameArea.canvas.height - 200;
gameObstacle.push(new obstacle(10, 200, "grey", x, y));
}
for(i=0 ; i<gameObstacle.length ; i++){
gameObstacle[i].x -= 1;
gameObstacle[i].update();
}
gameObstacle.x -= 1;
//giving co ordinates of cursor to game piece
gamePiece.x = gameArea.x;
gamePiece.y = gameArea.y;
gamePiece.update();
gamePiece.newPlace();
}
</script>
</body>
</html>

Related

The playable structure I am making in HTML falls flat, and the common attribute is not helping

I am trying to make a game in HTML with Java at the same time, and I do not know exactly how to color/paint the <canvas> element. Here is what I have so far with my game:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>
</body>
Why I want to color the canvas
The reason WHY i want to color the canvas is because I want to add a background, because this WILL be a public unofficial game. You can clearly see that the popular game: "Doodle Jump" (No clickbait) has a decent background color.
I want to be creative with my game, not lazy.
All in all, is <canvas> the best element? If so, how can I change the color of the background with CSS?
I made a fiddle with your code. In the fiddle I changed the background-color to yellow and it works.
You can also make the background of the canvas a different color by drawing a colored rectangle onto the canvas which has the same width and height as the canvas element. Just make sure to draw this rectangle before you draw anything else. Here's an example of what I mean:
// specify color
this.context.fillStyle = "red";
// draw a rectangle with the same width and height as canvas
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

How to make a prototype function use the values in a constructor

I am using the JavaScript canvas to make a pong-style game. I am attempting to use the values of the pong board's x and y grid values to create a prototype function for the ball to cause it to bounce off of the pong board whenever it touches. I have tried this a few different ways and I can't seem to get the ball to bounce off the pong board. I did not think that this aspect of the game's functionality would be the difficult part. I will provide snippets of the code below that I think are the problem:
var Pongboard = function() {
this.x = 15;
this.y = 15;
}
Ball.prototype.draw = function() {
makeBall(this.x, this.y, 5);
}
var pongboardValues = Object.values(Pongboard);
var pongX = pongboardValues[0];
var pongY = pongboardValues[1];
Ball.prototype.checkPongCollision = function() {
if (this.x < pongX && this.y < pongY) {
this.xSpeed = -this.xSpeed;
this.ySpeed = -this.ySpeed;
};
}
Any suggestions on how to get this working? Any hints would be greatly appreciated. If it helps, I will provide the full code below.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
//Create ball function
function makeBall (x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, false);
ctx.fill();
}
//Create pong board function
function makePong (x, y) {
ctx.fillRect(x, y, 10, 60);
}
//Ball construcor function
var Ball = function() {
this.x = width;
this.y = height/2;
this.xSpeed = 6;
this.ySpeed = Math.random()*8 - 2;
}
//Pong board constructor function
var Pongboard = function() {
this.x = 15;
this.y = 15;
}
//These are the values for the Pongboard object's location
var pongboardValues = Object.values(Pongboard);
var pongX = pongboardValues[0];
var pongY = pongboardValues[1];
Ball.prototype.draw = function() {
makeBall(this.x, this.y, 5);
}
Ball.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0 || this.x > width) {
this.xSpeed = -this.xSpeed;
};
if (this.y < 0 || this.y > height) {
this.ySpeed = -this.ySpeed;
};
}
Ball.prototype.checkPongCollision = function() {
if (this.x < pongX && this.y < pongY) {
this.xSpeed = -this.xSpeed;
this.ySpeed = -this.ySpeed;
};
}
Pongboard.prototype.draw = function() {
makePong(this.x, this.y);
}
var keyNames = {
38: "up",
40: "down"
};
Pongboard.prototype.moveUpAndDown = function(direction) {
if (direction==="up") {
this.y = this.y += -1*10;
};
if (direction==="down") {
this.y = this.y += 10;
};
};
var ball = new Ball();
var pong = new Pongboard();
$("#start-button").click(function() {
setInterval(function() {
ctx.clearRect(0, 0, width, height);
pong.draw();
ball.draw();
ball.move();
ctx.strokeRect(0, 0, width, height);
}, 30);
})
$("body").keydown(function(event) {
var direction = keyNames[event.keyCode];
pong.moveUpAndDown(direction);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start-button">Start</button><br>
<canvas width=300 height=200 id="canvas"></canvas>
Here I've got things working the way I think you want it.
You could extend this to make the ball bounce randomly on the Y axis too,..
I've commented out code that really wasn't doing anything too..
Also worth noting, you wasn't even calling checkPongCollision, so I've placed that in the timer.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
//Create ball function
function makeBall (x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, false);
ctx.fill();
}
//Create pong board function
function makePong (x, y) {
ctx.fillRect(x, y, 10, 60);
}
//Ball construcor function
var Ball = function() {
this.x = width;
this.y = height/2;
this.xSpeed = 6;
this.ySpeed = Math.random()*8 - 2;
}
//Pong board constructor function
var Pongboard = function() {
this.x = 15;
this.y = 15;
}
//These are the values for the Pongboard object's location
//not needed..
//var pongboardValues = Object.values(Pongboard);
//var pongX = pongboardValues[0];
//var pongY = pongboardValues[1];
Ball.prototype.draw = function() {
makeBall(this.x, this.y, 5);
}
Ball.prototype.move = function() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x < 0 || this.x > width) {
this.xSpeed = -this.xSpeed;
};
if (this.y < 0 || this.y > height) {
this.ySpeed = -this.ySpeed;
};
}
Ball.prototype.checkPongCollision = function() {
//if (this.x < pong.x && this.y < pong.y) {
if (
this.x >= pong.x && this.x < pong.x + 10 &&
this.y >= pong.y && this.y < pong.y + 60)
{
this.xSpeed = -this.xSpeed;
//this.ySpeed = -this.ySpeed;
};
}
Pongboard.prototype.draw = function() {
makePong(this.x, this.y);
}
var keyNames = {
38: "up",
40: "down"
};
Pongboard.prototype.moveUpAndDown = function(direction) {
if (direction==="up") {
this.y = this.y += -1*10;
};
if (direction==="down") {
this.y = this.y += 10;
};
};
var ball = new Ball();
var pong = new Pongboard();
$("#start-button").click(function() {
this.style.display = "none";
setInterval(function() {
ctx.clearRect(0, 0, width, height);
pong.draw();
ball.draw();
ball.move();
ctx.strokeRect(0, 0, width, height);
ball.checkPongCollision();
}, 30);
})
$("body").keydown(function(event) {
var direction = keyNames[event.keyCode];
pong.moveUpAndDown(direction);
});
body {
padding: 0;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button style="float:left" id="start-button">Start</button>
<canvas width=300 height=180 id="canvas"></canvas>

How to make gravity function interact with my image game piece?

I am working on a simple html game using a canvas and I am trying to figure out how to use an image that will react to the gravity function that im using. When I dont use the image and use a box instead it works perfectly fine but when I use the picture it stays in one place and then will not react with the game.
Here is the code that I have......
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "ship.png", 10, 120, "image");
myGamePiece.gravity = 5;
myScore = new component("30px", "Consolas", "#FF5733", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 300;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
}
else if (this.type == "image"){
shipImage = new Image() ;
shipImage.src= "ship.png" ;
shipImage.onload = function() {
ctx.drawImage( shipImage, 50, 50 )
}
}
else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 175;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(30, height, "white", x, 0));
myObstacles.push(new component(30, x - height - gap, "white", x, height + gap));
}

How can I create a function to draw a sprite on canvas?

I need to create function sprite() with canvas in javascript
I have 2 codes
this to create a sprite :
var width = 40,
height = 28,
frames = 2,
currentFrame = 0,
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
image = new Image()
image.src = 'http://s28.postimg.org/k90gybbtl/bird_Sprite.png';
var draw = function(){
ctx.clearRect(0, 0, width, height);
ctx.drawImage(image, 0, height * currentFrame, width, height, 0, 0, width, height);
if (currentFrame == frames) {
currentFrame = 0;
} else {
currentFrame++;
}
}
setInterval(draw, 120);
I have another code for simple game :
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myUpBtn = new component(canvasWidth, canvasHeight, "rgba(0, 0, 0, 0)", 0, 0);
myGameArea.start();
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
if (type == "image") {
ctx.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
}
this.clicked = function() {
var mytop = this.y;
var clicked = true;
if (mytop > myGameArea.y) {
clicked = false;
}
return clicked;
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
} // https://www.w3schools.com/graphics/game_images.asp
etc...
now the problem is ...
I can't make the 2 codes together
can anyone help me?
thank you :)
The following code adds your sprite to the game code from W3 Schools:
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(40, 28, "red", 10, 120, "sprite");
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
if (type === "sprite") {
this.currentFrame = 0;
this.frames = 2;
this.tickCount = 0;
this.ticksPerFrame = 4;
this.image = new Image();
this.image.src = 'http://s28.postimg.org/k90gybbtl/bird_Sprite.png';
}
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else if (this.type == "sprite") {
if (this.tickCount > this.ticksPerFrame) {
ctx.drawImage(this.image, 0, this.height * this.currentFrame, this.width, this.height, this.x, this.y, this.width, this.height);
this.tickCount = 0;
if (this.currentFrame == this.frames) {
this.currentFrame = 0;
} else {
this.currentFrame++;
}
} else {
ctx.drawImage(this.image, 0, this.height * this.currentFrame, this.width, this.height, this.x, this.y, this.width, this.height);
this.tickCount++;
}
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<body onload="startGame()">
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>
</body>
In summary:
Within the component function we initialise variables to handle the sprite animation if the type parameter is set to sprite
Within the update function we only draw the next frame of the sprite animation every 4th time update is called. This ensures that the sprite animation doesn't play to quickly
We then increment or reset the currentFrame count the same as you did before in your original code
If we're not ready to display the next frame in the sprite animation, we just display the existing frame again.
To take it further you might want to consider refactoring my solution so that the sprite is a separate "class" which inherits it's core functionality from component.

How to create mouseover highlight box in html 5?

If I have a 600 by 400 grid, with 10 by 10 pixel squares like this:
/**
* draws grid to screen
*/
function drawgrid(context)
{
for(var x = 0.5; x < 600; x += 10)
{
context.moveTo(x, 0);
context.lineTo(x, 400);
}
for(var y = 0.5; y < 400; y += 10)
{
context.moveTo(0, y);
context.lineTo(600, y);
}
context.strokeStyle = "#eee";
context.stroke();
}
/**
* Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
*/
function prepareCanvas()
{
var context = document.getElementById('canvas').getContext("2d");
drawgrid(context);
}
How would I mouseover the individual squares and highlight the square that the mouse is hovering over. Like make a red box highlighting the grid square the mouse is over.
See code below. Adjust coordinates for event
<body>
<canvas id=canvas height=400 width=600
onmousemove="over()" style="cursor:crosshair">
</canvas>
</body>
<script type="text/javascript">
<!--
var grid;
function prepareCanvasGrid()
{
var cnv = document.getElementById('canvas');
grid = new CanvasGrid(cnv.getContext("2d"),cnv.offsetLeft, cnv.offsetTop);
}
function CanvasGrid(context,x,y) {
this.sq = [];
this.dirty = [];
this.ctx = context;
this.x = x;
this.y = y;
this.init = function(){
for(var x = 0.5; x < 600; x += 50) {
for(var y = 0.5; y < 400; y += 50) {
var s = new square(x,y, context);
this.sq.push(s);
}
}
}
this.draw = function(){
this.ctx.clearRect(0,0,600,400);
for(var i=0; i < this.sq.length; i++)
this.sq[i].draw();
}
this.clean = function(){
for(var i=0; i < this.dirty.length; i++)
this.dirty[i].draw();
this.dirty = [];
}
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
}
}
}
this.init();
this.draw();
}
function square(x,y, ctx){
this.ctx = ctx;
this.x = x;
this.y = y;
this.h = 50;
this.w = 50;
this.draw = function(){
this.ctx.strokeStyle = "#eee";
this.ctx.strokeRect(this.x, this.y, this.w, this.w);
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.over = function() {
this.ctx.fillStyle = "red";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.eleAtPoint = function(ex,ey){
if(ex < this.x + this.w && ex > this.x
&& ey > this.y && ey < this.y + this.h)
return true;
return false;
}
}
function over(){
var e = window.event;
grid.over(e.clientX ,e.clientY);
}
prepareCanvasGrid();
//-->
</script>
Updated code for better performance
Just to add to hungryMind's answer, if you don't want any boxes to remain highlighted when the mouse is no longer over the canvas, add these two things:
1) An else if
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
} else if (!this.sq[i].eleAtPoint(ex,ey)) {
this.sq[i].off();
}
}
}
2) A square off() method:
this.off = function() {
this.draw();
}

Categories

Resources