从一个纹理文件中获取单独的纹理

时间:2013-02-12 08:29:03

标签: javascript jquery html5-canvas textures

我正在使用Canvas元素在Javascript中使用jQuery制作基于2D平铺的计算机游戏。我有一个图像文件,在一个文件中有多个纹理,如下图所示:

Example of texture file

例如,如果我知道每个纹理的宽度为50 px,那么我可以做什么drawTexture(id, canvas),其中id是纹理的ID从0开始(图片中的红色为0,绿色为1,蓝色为2,黄色为3),canvas是画布中的2D上下文。

1 个答案:

答案 0 :(得分:1)

使用drawImage中的slicing功能。

<img id="source" src="myTileSheet.png" style="display:none"/>
var columns    = 2,   //  The amount of tile columns,
    tileWidth  = 50,  //  Tile width,
    tileHeight = 50,  //  Tile height.
    image      = document.getElementById('source'),
    canvas     = document.getElementById('myCanvas'),
    ctx        = canvas.getContext('2d');

function drawTileAt(number, targetX, targetY){
    var sx = tileWidth * (Math.floor(number / columns)); // Get the X position.
    var sy = tileHeight * (number % columns);            // Y.

    // Where you want it on the canvas.
    ctx.drawImage(image,                  // Source image,
                  sx, sy,                 // Source X / Y to get the tile from,
                  tileWidth, tileHeight,  // Source Width / Height to crop out,
                  targetX, targetY,       // Destination X / Y to place the image,
                  tileWidth, tileHeight); // Destination W / H (can be used to scale a tile)
}

但是,这假设number从0开始计数。如果您希望第一个图块编号为1,请在函数的第一行添加:

number--;

所以:

function drawTile(number){
    number--;
    var image = document.getElementById('source');
    // etc.