mouse background image with canvas in html5 - html

I want something like this site , look at mouse background in header section:
Link
when i check page source i found this:
<canvas id="header-canvas" width="1360" height="676"></canvas>

Take a look at source code and identify which JS plugins are being used.
I have pulled it apart and found its using green sock https://greensock.com
Take a look at http://codepen.io/elliottgg/pen/YpQBpZ
Scroll down to line 40 to see where the magic is happening
(function() {
var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;
// Main
initHeader();
initAnimation();
addListeners();
function initHeader() {
width = window.innerWidth;
height = window.innerHeight;
target = {x: width/2, y: height/2};
largeHeader = document.getElementById('header');
largeHeader.style.height = height+'px';
canvas = document.getElementById('header-canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
// create points
points = [];
for(var x = 0; x < width; x = x + width/20) {
for(var y = 0; y < height; y = y + height/20) {
var px = x + Math.random()*width/20;
var py = y + Math.random()*height/20;
var p = {x: px, originX: px, y: py, originY: py };
points.push(p);
}
}
// for each point find the 5 closest points
for(var i = 0; i < points.length; i++) {
var closest = [];
var p1 = points[i];
for(var j = 0; j < points.length; j++) {
var p2 = points[j]
if(!(p1 == p2)) {
var placed = false;
for(var k = 0; k < 5; k++) {
if(!placed) {
if(closest[k] == undefined) {
closest[k] = p2;
placed = true;
}
}
}
for(var k = 0; k < 5; k++) {
if(!placed) {
if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
closest[k] = p2;
placed = true;
}
}
}
}
}
p1.closest = closest;
}
// assign a circle to each point
for(var i in points) {
var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.8)');
points[i].circle = c;
}
}
// Event handling
function addListeners() {
if(!('ontouchstart' in window)) {
window.addEventListener('mousemove', mouseMove);
}
window.addEventListener('scroll', scrollCheck);
window.addEventListener('resize', resize);
}
function mouseMove(e) {
var posx = posy = 0;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
target.x = posx;
target.y = posy;
}
function scrollCheck() {
if(document.body.scrollTop > height) animateHeader = false;
else animateHeader = true;
}
function resize() {
width = window.innerWidth;
height = window.innerHeight;
largeHeader.style.height = height+'px';
canvas.width = width;
canvas.height = height;
}
// animation
function initAnimation() {
animate();
for(var i in points) {
shiftPoint(points[i]);
}
}
function animate() {
if(animateHeader) {
ctx.clearRect(0,0,width,height);
for(var i in points) {
// detect points in range
if(Math.abs(getDistance(target, points[i])) < 4000) {
points[i].active = 0.3;
points[i].circle.active = 0.6;
} else if(Math.abs(getDistance(target, points[i])) < 20000) {
points[i].active = 0.1;
points[i].circle.active = 0.3;
} else if(Math.abs(getDistance(target, points[i])) < 40000) {
points[i].active = 0.02;
points[i].circle.active = 0.1;
} else {
points[i].active = 0.0;
points[i].circle.active = 0.0;
}
drawLines(points[i]);
points[i].circle.draw();
}
}
requestAnimationFrame(animate);
}
function shiftPoint(p) {
TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
onComplete: function() {
shiftPoint(p);
}});
}
// Canvas manipulation
function drawLines(p) {
if(!p.active) return;
for(var i in p.closest) {
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.closest[i].x, p.closest[i].y);
ctx.strokeStyle = 'rgba(255,255,255,'+ p.active+')';
ctx.stroke();
}
}
function Circle(pos,rad,color) {
var _this = this;
// constructor
(function() {
_this.pos = pos || null;
_this.radius = rad || null;
_this.color = color || null;
})();
this.draw = function() {
if(!_this.active) return;
ctx.beginPath();
ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'rgba(255,255,255,'+ _this.active+')';
ctx.fill();
};
}
// Util
function getDistance(p1, p2) {
return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
}

Related

HTML how to replace single colour object with picture? [duplicate]

This question already has answers here:
Change a shape on JavaScript canvas to become an image
(1 answer)
moving an image across a html canvas
(5 answers)
Closed 3 months ago.
I'm currently working on a simple HTML game and want to replace the yellow square with a picture. The yellow square's colour is defined by line 20, with "yellow". How can I make this a picture instead of a singular colour?
The line in question:
myGamePiece = new component(30, 30, "yellow", 10, 120);
This is what the game looks like currently:
This is ideally what the game will look like, hopefully it's a pretty simple fix but I can't figure out how to solve it.
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "yellow", 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;
}
window.addEventListener("DOMContentLoaded",startGame);
canvas {
border:1px solid #d3d3d3;
background-color: #3A93DC;
}
<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>

simulate onmouseup event to canvas

i have a simple HTML5 with a canvas object, i just need to add replicate the same events on the button below the code-
As you can see pushing the button, the canvas calls accelerate() and onmouseUp event calls the function again with different argument, and the canvas stops going up and starts with the gravity
I would like to use in a touch screen, the only problem is the event OnmuseUp that i do not know how to manage
this is the code:
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.canvas.addEventListener('click', function() {accelerate(-0.2);}, false);
updateGameArea();
},
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) {
if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}
myGamePiece.gravity = n;
}
<!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()">
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>
Rather than use the event listener to drive the game, use the event listener just to track the input state.
Eg
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {
active : false;
}
function inputEvent(){
input.active = true;
}
Then rather than use setInterval (which you should never use for animation) create a main loop function
function mainLoop(){
// see answer below
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
This will start being called every 1/60th second. In this you monitor the input and do what is needed depending on the game state.
const thrust = -0.4;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active && !inplay){
inplay = true;
input.active = false; // clear the input
}
if(inplay){
if(input.active){ // input
myGamePiece.speedY += thrust;
input.active = false; // clear input
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
You will need to change the move function
You had
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
Change to
this.newPos = function() {
this.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
Or you can change the input to have a thrust over some frames
const input = {
active : 0;
}
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
and change the main loop to
const thrust = -0.1;
const gravity = 0.1;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
Well everything is sort of like that, your game code is a little bit overly complex so I have hacked a quick mod to give you an example of what I meant in the above answer.
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : canvas,
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
this.frameNo = 0;
updateGameArea();
},
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.speedY += gravity;
this.x += this.speedX;
this.y += this.speedY;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
if(this.speedY > 0){
this.speedY = 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();
if (myGameArea.frameNo % wallFrameCount === 0 ) {
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();
myGameArea.frameNo += 1;
}
canvas.addEventListener("mousedown",inputEvent);
canvas.addEventListener("touchstart",inputEvent);
const input = {active : 0 };
const thrustFrameCount = 4;
function inputEvent(){
input.active = thrustFrameCount;
}
const wallFrameCount = 200;
const thrust = -0.4;
const gravity = 0.2;
var inplay = false; // when true game is playing.
function mainLoop(){
if(input.active > 0 && !inplay){
startGame();
inplay = true;
input.active = 0; // clear the input
}
if(inplay){
if(input.active > 0){ // input
myGamePiece.speedY += thrust * input.active;
input.active -= 1; // count down input on.
}
updateGameArea(); // call the render game function.
}
requestAnimationFrame(mainLoop); // get the next frame
}
requestAnimationFrame(mainLoop); // starts the first frame
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
<canvas id="canvas" width="480" height="270"></canvas><br>
Click touch canvas to start.

HTML5 Canvas Collision Detection

So I have been looking around and trying tutorials but I can't seem to get any collision detection systems to work. If someone would be able to explain what I am doing wrong or any syntax errors that would be great.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bouncing Ball</title>
<style>
#mycanvas {
outline: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="mycanvas" width="1280" height="750"></canvas>
<script>
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var xx = 50;
var yy = 100;
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity+=acceleration;
yy += velocity;
if(yy > 597) {
var temp =0;
temp =velocity/4;
velocity=-temp;
yy = 597;
}
}
function collision(first, second){
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: xx,
y: yy,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(xx, yy, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 300,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX+=3;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
xx += velX;
yy += velY;
physics();
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.rect(0,0,canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fill();
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
console.log('collision');
}
setTimeout(update, 10);
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
</script>
</body>
I can only append to what markE already says in his answer (we seem to be working on this simultaneously :) ).
I will first point out a more serious bug in the code:
You are using fill() without a beginPath() first. This will slow down the code loop rapidly. Replace fill() with a fillRect() instead.
Also, there is no need to use clearRect() when the next draw operation fills the entire canvas:
//ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fillRect(0, 0, canvas.width, canvas.height);
You're using global vars xx/yy. One main point of using objects is to avoid global vars. The render method uses the same so it appears to work, but the player's local properties are never updated. Remove global vars and only work with the object's x and y (I would recommend some refactoring so you can pass in the object to the physics() etc. instead of doing global referencing).
var xx = 50;var yy = 100;
To:
var player = {
x: 50, // numbers cannot be referenced, their value
y: 100, // is copied. Use these properties directly instead..
// ...
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height); // and here..
}
}
and
function physics() {
//...
player.y += velocity;
if (player.y > 597) {
//...
player.y = 597;
}
}
and in the loop:
player.x += velX;
player.y += velY;
Add preventDefault() in you key handlers to prevent the key moves to affect the brower's window scroll (not all users have a large screen so the left/right key will also affect the scrolling).
document.body.addEventListener("keydown", function(e) {
e.preventDefault();
...
And of course, use requestAnimationFrame to loop the animation.
I would also recommend using a function object that can be instantiated as you have methods in all of them. With a function object you can prototype the draw() method and share it across all the instances without the need of extra memory (and it's good for the internal optimizer as well). This if you plan to draw more than those three objects.
Updated code
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity += acceleration;
player.y += velocity;
if (player.y > 597) {
var temp = 0;
temp = velocity / 4;
velocity = -temp;
player.y = 597;
}
}
function collision(first, second) {
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: 50,
y: 100,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 300,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX += 3;
}
}
else if (keys[37]) {
if (velX > -speed) {
velX -= 3;
}
}
else if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
player.x += velX;
player.y += velY;
physics();
//ctx.clearRect(0, 0, canvas.width, canvas.height); // not really needed
ctx.fillStyle = "#EEE3B9";
ctx.fillRect(0, 0, canvas.width, canvas.height); // as this clears too...
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
console.log('collision');
}
requestAnimationFrame(update);
}
update();
document.body.addEventListener("keydown", function(e) {
e.preventDefault();
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
e.preventDefault();
keys[e.keyCode] = false;
});
#mycanvas {outline: 1px solid #000;}
<canvas id="mycanvas" width="1280" height="750"></canvas>
There's no problem with your collision function--it will correctly recognize the collision between any 2 un-rotated rectangles.
Visually, your black rect drops to the floor, bounces once or twice and then settles on the floor.
3 issues though...
I do see that your setTimeout is set to trigger every 10ms. That's a bit fast since the display will only refresh about every 1000/60=16.67ms--so your setTimeout should be at least 16.67. Also, You might consider using requestAnimationFrame instead of setTimeout because rAF synchronizes itself with the display and gives better performance.
One design glitch, even if the user constantly holds down the right-key to move the rect towards the bucket as fast as possible, the rect is never given enough "delta X" to hit the bucket.
You are testing collisions with player and bucket but you are not updating the player.x & player.y. Therefore your collision() is only testing the initial player position and not its current position.
// in update()
...
player.x=xx;
player.y=yy;
Demo of refactored code:
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var xx = 50;
var yy = 100;
var velY = 0;
var velX = 0;
var speed = 6;
var friction = 0.7;
var keys = [];
var velocity = 0;
var acceleration = 1;
function physics() {
velocity+=acceleration;
yy += velocity;
if(yy > 597) {
var temp =0;
temp =velocity/4;
velocity=-temp;
yy = 597;
}
}
function collision(first, second){
return !(first.x > second.x + second.width || first.x + first.width < second.x || first.y > second.y + second.height || first.y + first.height < second.y);
}
var player = {
color: "#2B2117",
x: xx,
y: yy,
width: 75,
height: 75,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(xx, yy, this.width, this.height);
}
}
var floor = {
color: "#A67437",
x: 0,
y: 670,
width: 1280,
height: 80,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var bucket = {
color: "#B25E08",
x: 50,
y: 600,
width: 50,
height: 100,
draw: function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function update() {
if (keys[39]) {
if (velX < speed) {
velX+=3;
}
}
if (keys[37]) {
if (velX > -speed) {
velX--;
}
}
if (keys[32]) {
velY -= 1.5;
velY += 1;
}
velX *= friction;
xx += velX;
yy += velY;
//
player.x=xx;
player.y=yy;
physics();
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.rect(0,0,canvas.width, canvas.height);
ctx.fillStyle = "#EEE3B9";
ctx.fill();
floor.draw();
bucket.draw();
player.draw();
if (collision(player, bucket)) {
alert('collision when player at:'+player.x+"/"+player.y);
}else{
setTimeout(update, 1000/60*3);
}
}
update();
document.body.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
<canvas id="mycanvas" width="1280" height="750"></canvas>
Copy and paste
<html>
<head>
<title> new </title>
<script>
var ctx1;
var ctx;
var balls = [
{x:50, y:50, r:20, m:1, vx:1, vy:1.5},
{x:200, y:80, r:30, m:1, vx:-1, vy:0.3},
];
function start()
{
ctx1 = document.getElementById("ctx");
ctx = ctx1.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = 2;
setInterval(draw, 10);
}
function draw()
{
ctx.clearRect(0, 0, ctx1.width, ctx1.height);
for (var a = 0; a < balls.length; a ++)
{
for (var b = 0; b < balls.length; b ++)
{
if (a != b)
{
var distToBalls = Math.sqrt(Math.pow(balls[a].x - balls[b].x, 2) + Math.pow(balls[a].y - balls[b].y, 2));
if (distToBalls <= balls[a].r + balls[b].r)
{
var newVel = getBallCollision(balls[a], balls[b]);
balls[a].vx = newVel.ball1.vx;
balls[a].vy = newVel.ball1.vy;
balls[b].vx = newVel.ball2.vx;
balls[b].vy = newVel.ball2.vy;
balls[a].x += balls[a].vx;
balls[a].y += balls[a].vy;
balls[b].x += balls[b].vx;
balls[b].y += balls[b].vy;
}
}
}
}
for (var a = 0; a < balls.length; a ++)
{
ctx.beginPath();
ctx.arc(balls[a].x, balls[a].y, balls[a].r, 0, Math.PI*2, true);
ctx.fill();
ctx.closePath();
if (balls[a].x <= balls[a].r) balls[a].vx *= -1;
if (balls[a].y <= balls[a].r) balls[a].vy *= -1;
if (balls[a].x >= ctx1.width - balls[a].r) balls[a].vx *= -1;
if (balls[a].y >= ctx1.height - balls[a].r) balls[a].vy *= -1;
balls[a].x += balls[a].vx;
balls[a].y += balls[a].vy;
}
}
function getBallCollision(b1, b2)
{
var dx = b1.x - b2.x;
var dy = b1.y - b2.y;
var dist = Math.sqrt(dx*dx + dy*dy);
if (Math.abs(dy) + Math.abs(dx) != 0 && dist <= b1.r + b2.r)
{
var colAng = Math.atan2(dy, dx);
var sp1 = Math.sqrt(b1.vx*b1.vx + b1.vy*b1.vy);
var sp2 = Math.sqrt(b2.vx*b2.vx + b2.vy*b2.vy);
var dir1 = Math.atan2(b1.vy, b1.vx);
var dir2 = Math.atan2(b2.vy, b2.vx);
var vx1 = sp1 * Math.cos(dir1 - colAng);
var vy1 = sp1 * Math.sin(dir1 - colAng);
var vx2 = sp2 * Math.cos(dir2 - colAng);
var vy2 = sp2 * Math.sin(dir2 - colAng);
var fvx1 = ((b1.m - b2.m) * vx1 + (2 * b2.m) * vx2) / (b1.m + b2.m);
var fvx2 = ((2 * b1.m) * vx1 + (b2.m - b1.m) * vx2) / (b1.m + b2.m);
var fvy1 = vy1;
var fvy2 = vy2;
b1.vx = Math.cos(colAng) * fvx1 + Math.cos(colAng + Math.PI/2) * fvy1;
b1.vy = Math.sin(colAng) * fvx1 + Math.sin(colAng + Math.PI/2) * fvy1;
b2.vx = Math.cos(colAng) * fvx2 + Math.cos(colAng + Math.PI/2) * fvy2;
b2.vy = Math.sin(colAng) * fvx2 + Math.sin(colAng + Math.PI/2) * fvy2;
return { ball1:b1, ball2:b2 };
}
else return false;
}
</script>
</head>
<body onLoad="start();">
<canvas id="ctx" width="500" height="300" style = "border : 2px solid #854125 ;"> </canvas>
</body>
</html>

Canvas Game Timer

I'm making a HTML5 Canvas Game with a rectangle that moves around the canvas. The objective is to dodge multiple Balls moving across the canvas for as long as possible. But i'm struggling to put a Timer to show your Time/Score when a ball hits the rectangle. (The rectangle is moved by the UP,DOWN,LEFT and RIGHT keys). Anyone with knowledge of this that could help me out would be much appreciated, thanks.
Here’s how to integrate a timer into your game:
Set the startingTime just before you start the game ticker:
/* Do the function, call every 20 milliseconds*/
startTime=new Date();
Draw the elapsed time whenever playGame is called:
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
// draw the score
drawElapsedTime();
}
And finally, draw the final score when the game is over:
drawFinalScore();
alert("GAME OVER");
Also, I noticed you left the game ticker running even after the game ended. Here’s how to turn off the ticker:
// turn on the ticker and get a reference to the object
var theInterval=setInterval(playGame, 20);
// turn off the ticker
clearInterval(theInterval);
And…check out the new requestAnimationFrame ticker. It’s much more efficient and resource friendly than the older setInterval ticker. Here’s a link for requestAnimationFrame: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/8qKht/
<!DOCTYPE html>
<html>
<head>
<style>
body
{
background-color:green;
}
#simpleCanvas
{
position: absolute;
top: 20%;
left: 30%;
border:2px solid blue;
width:500px;
height:500px;
background-color: yellow;
}
</style>
<script>
/* Ball Array */
var ball = new Array();
ball[0] = new Ball(150, 150); // x location of target, y location of target
ball[1] = new Ball(200, 350);
ball[2] = new Ball(400, 350);
ball[3] = new Ball(320, 250);
ball[4] = new Ball(440, 190);
ball[5] = new Ball(100, 350);
ball[6] = new Ball(80, 120);
ball[7] = new Ball(130, 240);
/* Player */
var player = new Player();
var score;
/* PLAYER OBJECT */
function Player()
{
/* private member variables */
var x = 10;
var y = 10;
var playerColour = "red";
var width = 25;
var height = 30;
var speed = 10;
/* public methods */
this.draw = draw;
function draw()
{
g.fillStyle = playerColour;
g.fillRect(x, y, width, height);
this.isHit();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getSpeed = getSpeed;
function getSpeed()
{
return speed;
}
this.getW = getW;
function getW()
{
return width;
}
this.getH = getH;
function getH()
{
return height;
}
this.isHit = isHit;
function isHit()
{
for (var i = 0; i < ball.length; i++)
{
if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
&& ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
{
clearInterval(theInterval);
drawFinalScore();
//alert("GAME OVER");
console.log("game over");
}
}
}
}
/* BALL OBJECT */
function Ball(newX, newY)
{
var x = newX;
var y = newY;
var dx = 2;
var dy = 4;
var radius = 10;
var targetColour = "blue";
/* public methods */
this.draw = draw;
function draw()
{
g.beginPath();
g.fillStyle = targetColour;
g.arc(x, y, radius, 0, Math.PI * 2);
g.fill();
g.closePath();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getRadius = getRadius;
function getRadius()
{
return radius;
}
this.move = move;
function move()
{
x += dx;
y += dy;
// Bounce on a left or right edge.
if (x + dx > canvas.width - radius || x + dx < radius)
{
dx = -dx;
}
// If ball hits the top, bounce it.
else if (y + dy < radius)
{
dy = -dy;
}
//If the ball hits the bottom, check see if it hits a paddle.
else if (y + dy > canvas.height - radius)
{
dy = -dy;
}
}
}
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
// draw the score
drawElapsedTime();
}
/* SCORE */
var startTime;
// ending elapsed time in seconds
var score;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
g.save();
g.beginPath();
g.fillStyle="red";
g.font="14px Verdana"
// draw the running time at half opacity
g.globalAlpha=0.50;
g.fillText(elapsed+" secs",canvas.width-75,25);
g.restore();
}
function drawFinalScore(){
// set the final score just once
if(score==null){ score=parseInt((new Date() - startTime)/1000); }
g.save();
g.beginPath();
g.fillStyle="red";
g.font="30px Verdana"
g.fillText("Game Over: "+score+" secs",50,35);
g.restore();
}
function arrowKeyDown(e)
{
var stepSize = 10; //Increase size
if (e.keyCode == 37) // left
{
player.setX(player.getX() - player.getSpeed());
if (player.getX() < 0)
{
player.setX(0);
}
}
else if(e.keyCode == 38) // up
{
player.setY(player.getY() - player.getSpeed());
if (player.getY() < 0)
{
player.setY(0);
}
}
else if(e.keyCode == 39) // right
{
player.setX(player.getX() + player.getSpeed());
if ((player.getX() + player.getW()) > canvas.width)
{
player.setX(canvas.width - player.getW());
}
}
else if(e.keyCode == 40) // down
{
player.setY(player.getY() + player.getSpeed());
if ((player.getY() + player.getH()) > canvas.height)
{
player.setY(canvas.height - player.getH());
}
}
}
document.addEventListener('keydown',arrowKeyDown);
</script>
</head>
<body>
<h1>A V O I D</h1>
<canvas id="simpleCanvas"></canvas>
<script>
/* Get the canvas id */
var canvas = document.getElementById("simpleCanvas");
/* Give the canvas a width and height */
/* The width and height are in canvas logical units */
canvas.width = 500;
canvas.height = 500;
/* Assign a graphics context to the canvas, so that we can draw on it */
var g = canvas.getContext("2d");
/* Do the function, call every 20 milliseconds*/
startTime=new Date();
var theInterval=setInterval(playGame, 20);
</script>
<audio src="intense.mp3" autoplay loop></audio>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<h1>
A V O I D
</h1>
<style>
body
{
background-color:green;
}
#simpleCanvas
{
position: absolute;
top: 20%;
left: 30%;
border:2px solid blue;
width:500px;
height:500px;
background-color: yellow;
}
}
</style>
<script>
/* Ball Array */
enter code here`var ball = new Array();
ball[0] = new Ball(150, 150); // x location of target, y location of target
ball[1] = new Ball(200, 350);
ball[2] = new Ball(400, 350);
ball[3] = new Ball(320, 250);
ball[4] = new Ball(440, 190);
ball[5] = new Ball(100, 350);
ball[6] = new Ball(80, 120);
ball[7] = new Ball(130, 240);
/* Player */
var player = new Player();
var score;
/* PLAYER OBJECT */
function Player()
{
/* private member variables */
var x = 10;
var y = 10;
var playerColour = "red";
var width = 25;
var height = 30;
var speed = 10;
/* public methods */
this.draw = draw;
function draw()
{
g.fillStyle = playerColour;
g.fillRect(x, y, width, height);
this.isHit();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getSpeed = getSpeed;
function getSpeed()
{
return speed;
}
this.getW = getW;
function getW()
{
return width;
}
this.getH = getH;
function getH()
{
return height;
}
this.isHit = isHit;
function isHit()
{
for (var i = 0; i < ball.length; i++)
{
if (((x + width) >= ball[i].getX()) && ((x + width) <= (ball[i].getX() + (ball[i].getRadius() * 2)))
&& ((y + height) >= ball[i].getY()) && ((y + height) <= (ball[i].getY() + (ball[i].getRadius() * 2))))
{
alert("GAME OVER");
}
}
}
}
/* BALL OBJECT */
function Ball(newX, newY)
{
var x = newX;
var y = newY;
var dx = 2;
var dy = 4;
var radius = 10;
var targetColour = "blue";
/* public methods */
this.draw = draw;
function draw()
{
g.beginPath();
g.fillStyle = targetColour;
g.arc(x, y, radius, 0, Math.PI * 2);
g.fill();
g.closePath();
}
this.setX = setX;
function setX(newX)
{
x = newX;
}
this.getX = getX;
function getX()
{
return x;
}
this.setY = setY;
function setY(newY)
{
y = newY;
}
this.getY = getY;
function getY()
{
return y;
}
this.getRadius = getRadius;
function getRadius()
{
return radius;
}
this.move = move;
function move()
{
x += dx;
y += dy;
// Bounce on a left or right edge.
if (x + dx > canvas.width - radius || x + dx < radius)
{
dx = -dx;
}
// If ball hits the top, bounce it.
else if (y + dy < radius)
{
dy = -dy;
}
//If the ball hits the bottom, check see if it hits a paddle.
else if (y + dy > canvas.height - radius)
{
dy = -dy;
}
}
}
/* MAIN GAME */
function playGame()
{
g.clearRect(0, 0, canvas.width, canvas.height); //Clear canvas at start.
player.draw();
for (var i = 0; i < 8; i++)
{
ball[i].move();
ball[i].draw();
}
}
/* SCORE */
var isGameOver=false;
var startTime;
// ending elapsed time in seconds
var score;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
ctx.save();
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="14px Verdana"
// draw the running time at half opacity
ctx.globalAlpha=0.50;
ctx.fillText(elapsed+" secs",canvas.width-75,25);
ctx.restore();
}
function drawFinalScore(){
// set the final score just once
if(score==null){ score=parseInt((new Date() - startTime)/1000); }
ctx.save();
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="18px Verdana"
ctx.fillText("Game Over: "+score+" secs",20,25);
ctx.restore();
}
function arrowKeyDown(e)
{
var stepSize = 10; //Increase size
if (e.keyCode == 37) // left
{
player.setX(player.getX() - player.getSpeed());
if (player.getX() < 0)
{
player.setX(0);
}
}
else if(e.keyCode == 38) // up
{
player.setY(player.getY() - player.getSpeed());
if (player.getY() < 0)
{
player.setY(0);
}
}
else if(e.keyCode == 39) // right
{
player.setX(player.getX() + player.getSpeed());
if ((player.getX() + player.getW()) > canvas.width)
{
player.setX(canvas.width - player.getW());
}
}
else if(e.keyCode == 40) // down
{
player.setY(player.getY() + player.getSpeed());
if ((player.getY() + player.getH()) > canvas.height)
{
player.setY(canvas.height - player.getH());
}
}
}
document.addEventListener('keydown',arrowKeyDown);
</script>
</head>
<body>
<canvas id="simpleCanvas">
Your browser does not support the HTML5 <canvas> tag.
</canvas>
<script>
/* Get the canvas id */
var canvas = document.getElementById("simpleCanvas");
/* Give the canvas a width and height */
/* The width and height are in canvas logical units */
canvas.width = 500;
canvas.height = 500;
/* Assign a graphics context to the canvas, so that we can draw on it */
var g = canvas.getContext("2d");
/* Do the function, call every 20 milliseconds*/
setInterval(playGame, 20);
</script>
<audio src="intense.mp3" autoplay loop></audio>
</body>
</html>
/*This is my code and i tryed adding it in and making it function but it would not work ? Dont know what im doing wrong ? Thanks for the reply

HTML5, Easel.js game problems

Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt