summaryrefslogtreecommitdiffstats
path: root/src/view
diff options
context:
space:
mode:
Diffstat (limited to 'src/view')
-rw-r--r--src/view/MapView.coffee81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/view/MapView.coffee b/src/view/MapView.coffee
new file mode 100644
index 0000000..4cd05de
--- /dev/null
+++ b/src/view/MapView.coffee
@@ -0,0 +1,81 @@
+'use strict'
+
+_ = require 'lodash'
+util = require '../util'
+
+
+tileSize = 32
+
+body = document.getElementsByTagName('body')[0]
+
+
+loadImage = (url) ->
+ new Promise (resolve, reject) ->
+ img = new Image()
+ img.addEventListener 'load', -> resolve img
+ img.addEventListener 'error', -> reject Error('Failed to load ' + url)
+ img.src = url
+
+loadImages = (imgs) ->
+ util.mapPromises(_.mapValues imgs, loadImage)
+
+loadTiles = (tileDef) ->
+ loadImages(_.mapValues tileDef, (t) -> "resources/sprite/tile/#{t.file}.png")
+
+
+class MapView
+ constructor: (@map, ready) ->
+ @redrawPending = false
+
+ @canvas = document.createElement 'canvas'
+ @ctx = @canvas.getContext '2d'
+ body.appendChild @canvas
+
+ body.addEventListener 'resize', @setSize
+
+ @setSize()
+
+ loadTiles(@map.tiles).then (tiles) =>
+ @tiles = tiles
+ @redraw()
+ ready()
+
+ drawTile: (x, y, tile) ->
+ return unless tile
+
+ @ctx.drawImage(tile, x, y)
+
+ draw: ->
+ @redrawPending = false
+
+ @ctx.clearRect 0, 0, @canvas.width, @canvas.height
+
+ return unless @tiles
+
+ for layer in @map.layers
+ y = 0
+
+ for row in layer
+ x = 0
+
+ for tile in row
+ @drawTile x, y, @tiles[tile]
+ x += tileSize
+
+ y += tileSize
+
+ redraw: ->
+ unless @redrawPending
+ @redrawPending = true
+ window.requestAnimationFrame => @draw()
+
+ setSize: ->
+ e = document.documentElement
+ @canvas.width = window.innerWidth || e.clientWidth || body.clientWidth
+ @canvas.height = window.innerHeight || e.clientHeight || body.clientHeight
+
+ @redraw()
+
+
+
+module.exports = MapView