-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTiledMapRenderer.js
86 lines (72 loc) · 1.84 KB
/
TiledMapRenderer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
module.exports = class TiledMapRenderer {
constructor( canvas, json ) {
this.json = json;
this.canvas = canvas;
this.tileMap = [];
this.setImageObject();
}
setImageObject() {
var ts = this.json.tilesets;
for ( var i = 0; i < ts.length; i++ ) {
ts[i].imageDOM = new Image();
ts[i].imageDOM.src = 'assets/' + ts[i].image;
}
}
getTile( index ) {
var ts = this.json.tilesets;
var min = 0;
var max = 0;
var trueIndex = 0;
var ox, oy;
for ( var i = 0; i < ts.length; i++ ) {
min = ts[i].firstgid;
max = min + ts[i].tilecount;
if ( index >= min && index < max ) {
trueIndex = index - min;
ox = (trueIndex % ts[i].columns) * ts[i].tilewidth;
oy = Math.floor( trueIndex / ts[i].columns ) * ts[i].tileheight;
return {
tile: ts[i],
offsetX: ox,
offsetY: oy
}
}
}
return false;
}
render( cam ) {
var thisTile, ox, oy;
var ctx = this.canvas.getContext( "2d" );
this.json.layers.forEach( function( layer, index ) {
if ( ! layer.visible )
return;
layer.data.forEach( function( cell, index ) {
thisTile = this.getTile( cell );
if ( thisTile ) {
ox = ( index % layer.width ) * thisTile.tile.tilewidth;
oy = Math.floor( index / layer.height ) * thisTile.tile.tileheight;
ox = ox - cam.x;
oy = oy - cam.y;
if (
ox > cam.w ||
oy > cam.h ||
ox < 0 - thisTile.tile.tilewidth ||
oy < 0 - thisTile.tile.tileheight
)
return;
ctx.drawImage(
thisTile.tile.imageDOM, // Image
thisTile.offsetX, // Origin offset
thisTile.offsetY,
thisTile.tile.tilewidth, // Origin size
thisTile.tile.tileheight,
ox, // Destination origin
oy,
thisTile.tile.tilewidth, // Destination width
thisTile.tile.tileheight
);
}
}, this );
}, this );
}
}