Reading JSON Tiled map editor file and displaying to canvas

白昼怎懂夜的黑 提交于 2019-12-03 03:45:00

Tiled + Canvas

I looked at the Tiled+Canvas blog post on http://blog.hashrocket.com/posts/using-tiled-and-canvas-to-render-game-screens by Shane Riley. An interesting post!

Good News…I grabbed his code from his demo and I have his code working locally on my development computer.

In going through the process and in looking at your code, I think you can get your code to work by taking care of 2 issues:

1) You have a small bug in your get_tileset function.

2) You need to point all of Shane’s demo files towards files located on your local computer. I just put all these files together in a single folder (worked for me). You will need to touch these files (details below):

  • mountain.html
  • mountain.json
  • mountain.tmx
  • mountain_landscape_23.png
  • render_scene.js

Here are the details. These worked for me and they should work for you. But if not, let me know and I can post my complete code.

A Bug -- In your get_tileset(), the tileset.onload is expecting a named function or inline function, not a function call.

// not this.tileset.onload=renderLayers(this)
this.tileset.onload=renderLayers;    

// change the signature of renderLayers 
// (you have “layers” in scope for visibility in this function so this s/b ok)
// So: not function renderLayers(layers)
function renderLayers()    

Please include an error catcher in your $.getJSON so you get visibility on failed requests!

$.getJSON('maps/'+ name + '.json', function(json){
        get_tileset(json);
}).fail( alert(“I think you should know that something has gone horribly wrong!”);  );

Here are the changes required to localize your files.

In mountain.html:

    <script src="render_scene.js" type="text/javascript"></script>

In render_scene.js (if you downloaded from the Gist)

load: function(name) {
  return $.ajax({
    url: "mountain.json",
    dataType: "text json"
  }).done($.proxy(this.loadTileset, this));
}

In mountain.json:

"image":"mountain_landscape_23.png",

In mountain.tmx:

<image source="mountain_landscape_23.png" width="512" height="512"/>

Mountain_landscape_23.png

Important! Depending on how you’ve got your development environment set up, you might get a cross-domain-security-error and the browser will refuse to draw your tiles. If so, take this png file into an editor like photoshop and save it back out to your dev domain to nullify the CORS error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!