【发布时间】:2017-10-24 10:45:13
【问题描述】:
我正在尝试做一个 Tilemap 系统,所以我完成了一个教程。这是代码:
// Possible tile types
const TILE_TYPES = {
0: { name: 'Sea', color: 'lightBlue'},
1: { name: 'Land', color: 'wheat' },
2: { name: 'House', color: 'black'}
}
// Map tile data
let mapData = <?php echo $mapData ?>
/**
Tile class
*/
class Tile {
constructor (size, type, ctx) {
this.size = size
this.type = type
this.ctx = ctx
}
draw (x, y) {
// Store positions
const xPos = x * this.size
const yPos = y * this.size
// Draw tile
this.ctx.fillStyle = this.type.color
this.ctx.fillRect(xPos, yPos, this.size, this.size)
}
}
/**
Map class
*/
class Map {
constructor (selector, data, opts) {
this.canvas = document.getElementById(selector)
this.ctx = this.canvas.getContext('2d')
this.data = data
this.tileSize = opts.tileSize
}
}
/**
OrthogonalMap class
*/
class OrthogonalMap extends Map {
constructor (selector, data, opts) {
super(selector, data, opts)
this.draw()
}
draw () {
const numCols = this.data[0].length
const numRows = this.data.length
// Iterate through map data and draw each tile
for (let y = 0; y < numRows; y++) {
for (let x = 0; x < numCols; x++) {
// Get tile ID from map data
const tileId = this.data[y][x]
// Use tile ID to determine tile type from TILE_TYPES (i.e. Sea or Land)
const tileType = TILE_TYPES[tileId]
// Create tile instance and draw to our canvas
new Tile(this.tileSize, tileType, this.ctx).draw(x, y)
}
}
}
}
// Init canvas tile map on document ready
document.addEventListener('DOMContentLoaded', function () {
// Init orthogonal map
const map = new OrthogonalMap('orthogonal-map', mapData, { tileSize: 64 })
})
来电:
<?php
$mapData = '[
[1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2],
[1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1],
[1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
]';
include "" . $_SERVER['DOCUMENT_ROOT'] . "/includes/maptiles.php";
?>
<canvas id="orthogonal-map" class="canvas-map" width="704" height="576"> </canvas>
这是我的问题:如何用图像替换颜色?
我的第一个赌注是将“color”属性替换为TILE_TYPES 常量,并将this.ctx.fillStyle 替换为this.ctx.drawimage。
我是 Javascript 的初学者,所以如果您有时间,我很想对您的流程进行一些解释。谢谢!
【问题讨论】:
标签: javascript canvas