在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.
太棒了!我假設代碼中的所有'50'都是寬度/高度?謝謝! – cpdt 2013-02-12 08:58:39
是的,確切地說。我會做一個編輯,把它們放在一個適當的變量中。 – Cerbrus 2013-02-12 09:00:35
@mrfishie:我讓它稍微高效一些,刪除了一些冗餘變量。 請記住,這隻能在瓷磚表面有鉛時使用。你可以使用像'image.addEventListener('load',init)'',其中'init'是一個啓動你的應用程序的函數。 – Cerbrus 2013-02-12 09:06:50