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
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 =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.