Canvas physics
Some basic movement physics in a the HTML5 canvas
by Anov Siradj
HTML
<script src="https://github.com/Wolfy87/Spark/raw/master/spark.js"></script>
<h1>Canvas physics</h1>
<p>Use the arrow keys! You will have to focus on this window first too.</p>
<canvas width='400' height='300'></canvas>
CSS
body {
background-color: #DDDDDD;
}
p {
color: #777777;
font-family: helvetica, arial, sans-serif;
-webkit-transform: rotate(8deg);
-moz-transform: rotate(8deg);
margin: 30px 0 0 0;
}
h1 {
color: #777777;
font-family: helvetica, arial, sans-serif;
font-size: 25pt;
-webkit-transform: rotate(-10deg);
-moz-transform: rotate(-10deg);
margin: 30px;
background-color: #EEEEEE;
float: left;
padding: 5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: 0 0 5px #777777;
-moz-box-shadow: 0 0 5px #777777;
box-shadow: 0 0 5px #777777;
}
canvas {
width: 400px;
height: 300px;
border: 3px solid #EEEEEE;
background-color: #FFFFFF;
margin: 30px auto;
display: block;
clear: both;
}
JavaScript
// Here lie ye options! As suggested by @js_fiddle
// Gravity - How strong you want the gravity, if false there will be none
window.gravity = 2;
// Jump - How high you wish to jump
window.jump = 25;
// Force - How much velocity you wish to be added while moving
window.force = 3;
// FPS - The amount of frames per second you wish to be run
window.fps = 40;
function draw() {
// Wipe canvas
ctx.clearRect(0, 0, 400, 300);
canvas.width = canvas.width;
// Apply friction - Reduce the velocity
if(box.velocity.x > 0)
box.velocity.x -= box.velocity.x / 10;
else if(box.velocity.x < 0)
box.velocity.x += box.velocity.x / -10;
if(gravity == false)
{
if(box.velocity.y > 0)
box.velocity.y -= box.velocity.y / 10;
else if(box.velocity.y < 0)
box.velocity.y += box.velocity.y / -10;
}
else
{
if(box.velocity.y > 0)
box.velocity.y -= 1;
else if(box.velocity.y < 0)
box.velocity.y += 1;
}
// Add gravity if needed
if(box.y < 250 && gravity !== false)
box.velocity.y += gravity;
// Add movers if needed - Increase the velocity accordingly
if(movers.up && box.y == 250 && gravity !== false)
box.velocity.y -= jump;
else if(movers.up && box.y > 0 && gravity === false)
box.velocity.y -= force;
if(movers.right && box.x < 350)
box.velocity.x += force;
if(movers.down && box.y < 250)
box.velocity.y += force;
if(movers.left && box.x > 0)
box.velocity.x -= force;
// Apply velocity
box.x += box.velocity.x;
box.y += box.velocity.y;
// Add wall collisions
if(box.x < 0)
{
// Hitting the left wall
box.x = 0;
box.velocity.x -= box.velocity.x * 1.4;
}
else if(box.x > 350)
{
// Hitting the right wall
box.x = 350;
box.velocity.x -= box.velocity.x *...