Canvas Game Timer - html

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

Related

How do I allow pointer-events on an HTML5 canvas background while allowing links and buttons to receive pointer-events, too?

I set an HTML5 canvas to a background that looks like interlinked nodes (link). The canvas element works as expected but when I set it to be the background of the page, I couldn't click on links or buttons on the page.
When I set the canvas background to the back of all elements by either declaring a z-index value or editing the HTML so that it's the first element, I can normally click on links, but every time a pointer-event is active on a button (such as a hover) it stops the canvas background from getting the mouse pointer's location.
I expect it's got something to do with the pointer-events, but I can't move past this because I'm unsure as to what to do.
Supposing that you put the content of your document in a div #wrap with a position absolute over the canvas, in order to interact with the particles on canvas you may use the mouse position over the #wrap. In your example I'm using wrap.addEventListener('mousemove', mousemoveHandler, false); instead of canvas.addEventListener('mousemove', mousemoveHandler, false);
(function() {
var canvas, ctx, circ, nodes, mouse, SENSITIVITY, SIBLINGS_LIMIT, DENSITY, NODES_QTY, ANCHOR_LENGTH, MOUSE_RADIUS;
// how close next node must be to activate connection (in px)
// shorter distance == better connection (line width)
SENSITIVITY = 100;
// note that siblings limit is not 'accurate' as the node can actually have more connections than this value that's because the node accepts sibling nodes with no regard to their current connections this is acceptable because potential fix would not result in significant visual difference
// more siblings == bigger node
SIBLINGS_LIMIT = 10;
// default node margin
DENSITY = 50;
// total number of nodes used (incremented after creation)
NODES_QTY = 0;
// avoid nodes spreading
ANCHOR_LENGTH = 20;
// highlight radius
MOUSE_RADIUS = 200;
circ = 2 * Math.PI;
nodes = [];
canvas = document.querySelector('canvas');
resizeWindow();
mouse = {
x: canvas.width / 2,
y: canvas.height / 2
};
ctx = canvas.getContext('2d');
if (!ctx) {
alert("Ooops! Your browser does not support canvas :'(");
}
function Node(x, y) {
this.anchorX = x;
this.anchorY = y;
this.x = Math.random() * (x - (x - ANCHOR_LENGTH)) + (x - ANCHOR_LENGTH);
this.y = Math.random() * (y - (y - ANCHOR_LENGTH)) + (y - ANCHOR_LENGTH);
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
this.energy = Math.random() * 100;
this.radius = Math.random();
this.siblings = [];
this.brightness = 0;
}
Node.prototype.drawNode = function() {
var color = "rgba(255, 0, 0, " + this.brightness + ")";
ctx.beginPath();
ctx.arc(this.x, this.y, 2 * this.radius + 2 * this.siblings.length / SIBLINGS_LIMIT, 0, circ);
ctx.fillStyle = color;
ctx.fill();
};
Node.prototype.drawConnections = function() {
for (var i = 0; i < this.siblings.length; i++) {
var color = "rgba(255, 0, 0, " + this.brightness + ")";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.siblings[i].x, this.siblings[i].y);
ctx.lineWidth = 1 - calcDistance(this, this.siblings[i]) / SENSITIVITY;
ctx.strokeStyle = color;
ctx.stroke();
}
};
Node.prototype.moveNode = function() {
this.energy -= 2;
if (this.energy < 1) {
this.energy = Math.random() * 100;
if (this.x - this.anchorX < -ANCHOR_LENGTH) {
this.vx = Math.random() * 2;
} else if (this.x - this.anchorX > ANCHOR_LENGTH) {
this.vx = Math.random() * -2;
} else {
this.vx = Math.random() * 4 - 2;
}
if (this.y - this.anchorY < -ANCHOR_LENGTH) {
this.vy = Math.random() * 2;
} else if (this.y - this.anchorY > ANCHOR_LENGTH) {
this.vy = Math.random() * -2;
} else {
this.vy = Math.random() * 4 - 2;
}
}
this.x += this.vx * this.energy / 100;
this.y += this.vy * this.energy / 100;
};
function initNodes() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
nodes = [];
for (var i = DENSITY; i < canvas.width; i += DENSITY) {
for (var j = DENSITY; j < canvas.height; j += DENSITY) {
nodes.push(new Node(i, j));
NODES_QTY++;
}
}
}
function calcDistance(node1, node2) {
return Math.sqrt(Math.pow(node1.x - node2.x, 2) + (Math.pow(node1.y - node2.y, 2)));
}
function findSiblings() {
var node1, node2, distance;
for (var i = 0; i < NODES_QTY; i++) {
node1 = nodes[i];
node1.siblings = [];
for (var j = 0; j < NODES_QTY; j++) {
node2 = nodes[j];
if (node1 !== node2) {
distance = calcDistance(node1, node2);
if (distance < SENSITIVITY) {
if (node1.siblings.length < SIBLINGS_LIMIT) {
node1.siblings.push(node2);
} else {
var node_sibling_distance = 0;
var max_distance = 0;
var s;
for (var k = 0; k < SIBLINGS_LIMIT; k++) {
node_sibling_distance = calcDistance(node1, node1.siblings[k]);
if (node_sibling_distance > max_distance) {
max_distance = node_sibling_distance;
s = k;
}
}
if (distance < max_distance) {
node1.siblings.splice(s, 1);
node1.siblings.push(node2);
}
}
}
}
}
}
}
function redrawScene() {
resizeWindow();
ctx.clearRect(0, 0, canvas.width, canvas.height);
findSiblings();
var i, node, distance;
for (i = 0; i < NODES_QTY; i++) {
node = nodes[i];
distance = calcDistance({
x: mouse.x,
y: mouse.y
}, node);
if (distance < MOUSE_RADIUS) {
node.brightness = 1 - distance / MOUSE_RADIUS;
} else {
node.brightness = 0;
}
}
for (i = 0; i < NODES_QTY; i++) {
node = nodes[i];
if (node.brightness) {
node.drawNode();
node.drawConnections();
}
node.moveNode();
}
requestAnimationFrame(redrawScene);
}
function initHandlers() {
document.addEventListener('resize', resizeWindow, false);
///////////////////////////////////
wrap.addEventListener('mousemove', mousemoveHandler, false);
///////////////////////////////////
}
function resizeWindow() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function mousemoveHandler(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
initHandlers();
initNodes();
redrawScene();
})();
html,
body {
margin: 0;
background-color: #25003a;
overflow: hidden;
}
canvas {
position: relative;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: #25003a;
overflow: hidden;
}
#wrap {
position: absolute;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
line-height: 100vh;
}
#wrap p {
text-align: center;
border: 1px solid;
}
#wrap p a {
color: white;
font-size: 70px;
text-decoration: none;
}
#wrap p a:hover {
text-decoration: underline;
}
<canvas></canvas>
<div id="wrap">
<p>
this is a link</p>
</div>

html5 game object movement not working

I am trying to improve my html5 game that I am creating, I am trying to put player object movement into the game like so :
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
theplayer = function(width, height, color, x, y)
{
this.width = width;
this.height = height;
this.color = color;
this.speedx = 0;
this.speedy = 0;
this.x = x;
this.y = y;
this.update=function()
{
context.fillStyle = color;
context.fillRect(this.x,this.y,this.width,this.height);
}
this.newpos=function()
{
this.x += this.speedx;
this.y += this.speedy;
}
}
var theplayer = new theplayer(30, 30, "red", 10, 120);
function clearboard()
{
context.clearRect(0,0,canvas.width,canvas.height);
}
function movement()
{
document.addEventListener("keydown",keyPressed, false);
document.addEventListener("keyup",keyLifted, false);
}
function keyPressed(event)
{
var keyPressed = String.fromCharCode(event.keyCode);
if (keyPressed == "W")
{
theplayer.speedx += 1;
}
else if (keyPressed == "D")
{
theplayer.speedy += 1;
}
else if (keyPressed == "S")
{
theplayer.speedx -= 1;
}
else if (keyPressed == "A")
{
theplayer.speedy -= 1;
}
}
var rungame = setInterval(function()
{
clearboard();
theplayer.newpos();
theplayer.update();
}, 20);
The program should make the player control the player object with the WASD keys but I am unable to make the change of X and Y coordinates apply to 'theplayer' object into the 'newpos' function. How can I solve the problem and is there anyway to put multiple key stroke presses of the WASD keys ?

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.

mouse background image with canvas in html5

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);
}

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>