我想使用 spritesheet 来减少图 block 游戏的 HTTP 请求次数。
假设有大约 2000 个不同类型的图 block ,则每次加载游戏时会减少 2000 个请求。
Sprite 高 64 像素,包含 64 x 64 像素图 block 。
以下代码检索单个图像并开始渲染:
var tiles = new Image();
tiles.src = "tiles.png";
tiles.onload = function() {
startRendering();
};
我的问题是,如何从中检索单个 Image 对象?
最佳答案
使用纯 JS 无法做到这一点。恐怕您将不得不使用一些 CSS 来实现这一点。
例如,假设您有一个
而不是img
<span class="imageholder" style="padding: 64px;"></span>
现在在您的 JavaScript 中,您可以使用以下内容
...
tiles.backgroundImage = 'url(tiles.png)';
tiles.backgroundPosition = '0px 0px'; // apply the position to get any of the image at any position
...
关于Javascript 从 Sprite 获取图像对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075485/