2013-06-05 84 views
1

我正在制作一个游戏,世界地图将从名为Tiles的块创建。所有瓷砖都保存在单个PNG文件,类似于下面贴:如何将图像分成几个部分? Tilemap

enter image description here

我需要划分这种图像并单独存放在内存中的所有这些块,这样我就可以在屏幕上绘制这些砖所需顺序。

这样做的最佳方式是什么,所以它在每个Web浏览器中都能正常工作?

回答

1

有一些有用的框架,如Pixi.js。但是如果你想避免使用canvas或巨大的框架,你也可以使用CSS。

.tile { 
 
    width: 64px; 
 
    height: 64px; 
 
    background-image: url(http://i.stack.imgur.com/TO5jy.png); 
 
    float: left; 
 
} 
 

 
.tile.tile-floor { 
 
    background-position: 0px 0px; 
 
} 
 

 
.tile.tile-wall { 
 
    background-position: -64px 0px; 
 
} 
 

 
.tile.tile-blue { 
 
    background-position: -192px -192px; 
 
}
<div class="tile tile-blue"></div> 
 
<div class="tile tile-floor"></div> 
 
<div class="tile tile-wall"></div>

0

看看下面这个例子,可能是这将帮助你。 http://jsfiddle.net/elclanrs/HmpGx/

(function($, window) { 

    var _defaults = { 
    x : 3, // tiles in x axis 
    y : 3, // tiles in y axis 
    gap: 2 
    }; 

    $.fn.splitInTiles = function(options) { 

    var o = $.extend({}, _defaults, options); 

    return this.each(function() { 

     var $container = $(this), 
      width = $container.width(), 
      height = $container.height(), 
      $img = $container.find('img'), 
      n_tiles = o.x * o.y, 
      wraps = [], $wraps; 

     for (var i = 0; i < n_tiles; i++) { 
     wraps.push('<div class="tile"/>'); 
     } 

     $wraps = $(wraps.join('')); 

     // Hide original image and insert tiles in DOM 
     $img.hide().after($wraps); 

     // Set background 
     $wraps.css({ 
     width: (width/o.x) - o.gap, 
     height: (height/o.y) - o.gap, 
     marginBottom: o.gap +'px', 
     marginRight: o.gap +'px', 
     backgroundImage: 'url('+ $img.attr('src') +')' 
     }); 

     // Adjust position 
     $wraps.each(function() { 
     var pos = $(this).position(); 
     $(this).css('backgroundPosition', -pos.left +'px '+ -pos.top +'px'); 
     }); 

    }); 

    }; 

}(jQuery, window)); 

$('div').splitInTiles(); 
5

单纯看画布drawImage方法:使用其所有参数时,媒体链接允许选择性复制图像的一部分。

var tileIndex = 3; // index of the tile within the texture image 
var tileWidth=16, tileHeight = 16; 
var tilePerLine = 6; 
var offsetX  = (tileIndex % tilePerLine)*tileWidth; 
var offsetY  = Math.floor(tileIndex/tilePerLine) * tileHeight; 

ctx.drawImage(thisImage, offsetX, offsetY, tileWidth, tileHeight, x, y); 
0

你可以使用“图像精灵”的概念使用CSS来做到这一点。

如果你的游戏有4 x 4格,那么你将不得不创建16 <div>,每个div设置background-image: url(image.jpg)background-position:-left -top
请阅读有关background-position以更好地理解它。 (http://www.csslessons.com/

然后,您只需要在用户点击图块时更改<div>的位置。