A-STAR Pathfinding for HTML5 Canvas by @McFunkypants
A demonstration of a-star pathfinding in javascript using HTML5 canvas. Prepared for www.buildnewgames.com Made by @McFunkypants http://www.mcfunkypants.com http://twitter.com/McFunkypants
by Andrew Gerst
HTML
<div>
HTML5 Pathfinding Tutorial by
<a href='http://twitter.com/McFunkypants'>@McFunkypants</a>
<input type='button' onClick='createWorld()' value='New World'>
</div>
<div><canvas id="gameCanvas"></canvas></div>
CSS
body { padding:0; margin:0; height:100%; width:100%; }
div { font-family:arial; font-size:16px; font-weight:bold; text-align:center; }
JavaScript
// A* Pathfinding for HTML5 Canvas Tutorial
// by Christer (McFunkypants) Kaitila
// http://www.mcfunkypants.com
// http://twitter.com/McFunkypants
// Based on Edsger Dijkstra's 1959 algorithm and work by:
// Andrea Giammarchi, Alessandro Crugnola, Jeroen Beckers,
// Peter Hart, Nils Nilsson, Bertram Raphael
// Permission is granted to use this source in any
// way you like, commercial or otherwise. Enjoy!
// the game's canvas element
var canvas = null;
// the canvas 2d context
var ctx = null;
// an image containing all sprites
var spritesheet = null;
// true when the spritesheet has been downloaded
var spritesheetLoaded = false;
// the world grid: a 2d array of tiles
var world = [[]];
// size in the world in sprite tiles
var worldWidth = 16;
var worldHeight = 16;
// size of a tile in pixels
var tileWidth = 32;
var tileHeight = 32;
// start and end of path
var pathStart = [worldWidth,worldHeight];
var pathEnd = [0,0];
var currentPath = [];
// ensure that concole.log doesn't cause errors
if (typeof console == "undefined") var console = { log: function() {} };
// the html page is ready
function onload()
{
console.log('Page loaded.');
canvas = document.getElementById('gameCanvas');
canvas.width = worldWidth * tileWidth;
canvas.height = worldHeight * tileHeight;
canvas.addEventListener("click", canvasClick, false);
if (!canvas) alert('Blah!');
ctx = canvas.getContext("2d");
if (!ctx) alert('Hmm!');
spritesheet = new Image();
// spritesheet.src = 'spritesheet.png';
// the image above has been turned into a data url
// so that no external files are required for
// this web page - useful for included in a
// "gist" or "jsfiddle" page
spritesheet.src =...