summaryrefslogtreecommitdiffstats
path: root/src/view
diff options
context:
space:
mode:
authorMatthias Schiffer <mschiffer@universe-factory.net>2016-01-05 18:10:35 +0100
committerMatthias Schiffer <mschiffer@universe-factory.net>2016-01-05 18:10:35 +0100
commit3280ab57bffb3fa1018d406eb25a3d98564a51d7 (patch)
tree02c5d76d89b94b964a7cc005531c6c4427666bc0 /src/view
parentb910818f176d009a9b98a419b645b6c7e1cb1d20 (diff)
downloadrpgedit-3280ab57bffb3fa1018d406eb25a3d98564a51d7.tar
rpgedit-3280ab57bffb3fa1018d406eb25a3d98564a51d7.zip
Implement basic map rendering
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