Question

Is there any function in javascript that can read a .tmx image file and draw it inside an html5 canvas using the default drawing funcion of images inside the canvas context.drawImage(img,x,y,cw,ch) ?

Was it helpful?

Solution

Unfortunately no, TMX file format are not directly supported in JavaScript so you'll have to write a parser for it.

The following page describes how to parse a TMX file (I cannot paste any content from that page due to size and copyright/license). The code is for ActionScript, an ECMA-script cousin of JavaScript, so the code itself is not so hard to port:

Parse TMX files

As to load and parse the XML itself: JavaScript has a built in XML parser, the XMLHttpRequest object, which you load the file with, combined with the DOMParser, see this answer for how:

Parse XML with JavaScript

If you don't want to write it yourselves you can take a look at for example the GameJS library which has a built-in TMX parser. The library is MIT licensed so you are free to use its code or part of its code in your own project(s).

After the file has been parsed you also need to have code to put the tiles on the canvas. A simple 2D tile engine is easy to make. You can use for example this as a starting point (it's not JavaScript but the code is easy to read and to port):

A simple 2D tile engine

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top