2013-02-12 81 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