Last Good Quote: Son's are the seasoning on our lives. - Someone on Facebook

Monday, March 29

Code: Simple 2D Javascript Map

A friend of mine asked me what is the quickest, simplest way to create a 2d map. Think top down, grid like map.

Here is 35 lines of javascript code that will do just that. Enjoy...


<html>
<style>
.tile {
background:#BBB;
border:1px solid #999;
position:absolute;
top:0px;left:0px;
width:5px;height:5px;
overflow:hidden
}
</style>
<script language=javascript>

var originX = 0;
var originY = 0;
var tileSize = 32;

function buildMap(width, height)
{
for(x=0;x<width;x++)
for(y=0;y<height;y++)
{
var d = document.createElement("DIV");
d.className="tile";
d.setAttribute("ID","tile_" + x + "_" + y);
d.style.top = originY + (y*tileSize);
d.style.left = originX + (x*tileSize);
d.style.width = tileSize;
d.style.height = tileSize;
document.getElementById("divMap").appendChild(d);
}
}


</script>
<body onload="buildMap(10,10)">

<div id="divMap"></div>

</body>
</html>

0 comments:

Post a Comment

Followers