Skip to content

Instantly share code, notes, and snippets.

@ralphsaunders
Created October 31, 2011 14:52
Show Gist options
  • Save ralphsaunders/1327654 to your computer and use it in GitHub Desktop.
Save ralphsaunders/1327654 to your computer and use it in GitHub Desktop.
Basic Canvas Animation
<!doctype html>
<html>
<head>
<title>Canvas Stuff</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="./scripts.js"></script>
</head>
<body id="index">
<canvas id="canvas" width="900" height="900">
<!-- Fallback men, fallback! -->
</canvas>
</body>
</html>
$( document ).ready( function() {
var canvas = document.getElementById( 'canvas' ); // Need to use getElementById, annoyingly
var space = canvas.getContext( '2d' );
/**
* Clear
*
* Clears whole canvas from origin 0, 0 (x, y)
*/
function clear() {
space.clearRect( 0, 0, canvas.width, canvas.height );
}
/**
* Draw Rectangle
*
* Draws rectangle on canvas when given coordinates.
*
* @param x int
* @param y int
*/
function drawTang( x, y ) {
space.fillStyle = "blue"; // Will take pretty much all colour codes
space.fillRect( x, y, 100, 100 );
}
/**
* Generate Coordinates
*
* Generates x and y coordinates between 0 and 100
*
* @return array[ x, y ];
*/
function genCoords() {
var x = Math.floor( Math.random() * 11 * 10 );
var y = Math.floor( Math.random() * 11 * 10 );
return [ x, y ];
}
/**
* Initiate
*
* Clears canvas;
* Grabs random coords;
* Draws rectangle
*/
function init() {
clear();
var coords = genCoords();
drawTang( coords[0], coords[1] );
}
// Every 100 miliseconds run init();
var interval = window.setInterval( init, 100 );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment