2013-02-12 75 views
0

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

Example of texture file

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

回答

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. 
+0

太棒了!我假设代码中的所有'50'都是宽度/高度?谢谢! – cpdt 2013-02-12 08:58:39

+0

是的,确切地说。我会做一个编辑,把它们放在一个适当的变量中。 – Cerbrus 2013-02-12 09:00:35

+0

@mrfishie:我让它稍微高效一些,删除了一些冗余变量。 请记住,这只能在瓷砖表面有铅时使用。你可以使用像'image.addEventListener('load',init)'',其中'init'是一个启动你的应用程序的函数。 – Cerbrus 2013-02-12 09:06:50