在画布中绘制平铺地图

时间:2014-01-30 22:04:47

标签: javascript html canvas

我正在尝试使用64x64可平铺图像在HTML5 Canvas上绘制一个平铺贴图。它们被命名为1.png,2.png和3.png。它们只是64x64图像,我打算用它们在画布背景上平铺。 1.png是纯绿色图像,2.png是纯灰色图像,3.png是纯棕色图像。
这是我的HTML:

<canvas id='gameCanvas'></canvas>
<script src='Index.js'></script>

这是我的JavaScript:

var canvas = document.getElementById('gameCanvas'),
ctx = canvas.getContext('2d');
canvas.width = 512;
canvas.height = 512;
var map = ['2','2','2','2','2','2','2','2','2','2',
        '2','1','1','1','1','3','1','1','1','2',
        '2','1','1','1','1','3','1','1','1','2',
        '2','2','2','2','2','2','2','2','2','2'],
x = 0,
y = 0,
image = new Image();

for (var j = 0; j < map.length; j++){
    image.onload = function(){
        if(x == 512){
            x = 0;
         y += 64;
    }
    x += 64;
    ctx.drawImage(image, x, y);
}
image.src = 'Images/' + map[j] + '.png';
}

出于某种原因,它似乎是在一个地方绘制所有图像。我认为它与image.onload = functtion(){}有关。任何人都可以帮我制作这段代码,将每个图像64像素(图像的宽度和高度)分开。

1 个答案:

答案 0 :(得分:-1)

您需要在onload处理程序中启动循环。在循环内部进行onload只会触发一次(当图像加载时,而不是因为循环)。

image.onload = function(){
    for (var j = 0; j < map.length; j++){
        /// todo: actually use map index to determine source rectangle
        /// in spritesheet
        if(x == 512){
            x = 0;
            y += 64;
        }
        x += 64;
        ctx.drawImage(this, x, y);  /// todo: need to specify sprite rectangle
    }
}

您可能还需要为drawImage()方法指定源矩形,但由于您没有显示我们无法分辨的图像(您的循环也会忽略地图图块索引)。

<强>更新

好的,根据评论,这是一个使用集成到原始代码中的YAIL加载器(如建议的)加载图像的示例(假设已包含脚本):

Demo (with random tiles)

var canvas = document.getElementById('gameCanvas'),
    ctx = canvas.getContext('2d');

canvas.width = 512;
canvas.height = 512;

var map = [2,2,2,2,2,2,2,2,2,2,  /// use numbers instead of strings here
           2,1,1,1,1,3,1,1,1,2,
           2,1,1,1,1,3,1,1,1,2,
           2,2,2,2,2,2,2,2,2,2],
    x = 0,
    y = 0,

    /// loader code
    loader = (new YAIL({
        done: drawTiles,                    /// called when images are loaded
        urls: ['1.png', '2.png', '3.png']   /// order will be preserved
    })).load();                             /// start loading

function drawTiles(e) {

    /// loop and get map index
    for (var j = 0, tile; tile = map[j]; j++){
        if(x == 512){
            x = 0;
            y += 64;
        }
        ctx.drawImage(e.images[tile - 1], x, y);
        x += 64;
    }
}

还应为最终代码添加错误处理程序。