javascript - 如何使用 Javascript 从纹理图集中获取图像?

标签 javascript html5-canvas

包含 Sprite 的 Sprite 表图像对象...

var spritesheet = new Image(); spritesheet.src ="foo.png";

我希望能够从该 spritesheet 变量中获取具有所需 x、y、宽度和高度的子图像。然后分配一个变量,该变量是 spritesheet 的子图像。

我该怎么做?

最佳答案

使用 divbackgroundPosition让这变得很容易,因为它会为我们自动剪辑,而无需使用溢出

例如,这里是 texture atlas来自流行的Cookie Clicker闲置游戏。

使用 x 和 y 的偏移量,我们可以从纹理图集中选择一个子 Sprite :

// Inputs -- change this based on your art
var tw  = 48; // Texture Atlas Tile Width (pixels)
var th  = 48; // Texture Atlas Tile Height (pixels)
var tx  =  3; // tile index x (relative) (column)
var ty  =  2; // tile index y (relative) (row)
var src = 'http://orteil.dashnet.org/cookieclicker/img/icons.png';

// Calculations -- common code to sub-image of texture atlas
var div = document.getElementById('clip');
var x   = (tx*tw); // tile offset x position (absolute)
var y   = (ty*th); // tile offset y position (absolute)
div.style.width              = tw + 'px';
div.style.height             = th + 'px';
div.style.backgroundImage    = "url('" + src + "')";
div.style.backgroundPosition = '-' + x + 'px -' + y + 'px';

// You don't need the remaining parts. They are only to
// show the sub-sprite in relation to the texture atlas
div.style.border             = "1px solid blue"; // only for demo purposes

// highlight where in the original texture the sub sprite is

var rect    = document.getElementById('sprites').parentNode.getBoundingClientRect();
var hi      = document.getElementById('highlight');
hi.style.zIndex   = 999; // force to be on top
hi.style.position = "absolute";
hi.style.width    = tw + 'px';
hi.style.height   = th + 'px';
hi.style.left     = (rect.left     + x) + 'px';
hi.style.top      = (rect.top + th + y) + 'px'; // skip sub-sprite height
hi.style.border   = '1px solid red';
<div id="clip"></div>
<img id="sprites" src="http://orteil.dashnet.org/cookieclicker/img/icons.png">
<div id="highlight"></div>

关于javascript - 如何使用 Javascript 从纹理图集中获取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004585/

相关文章:

javascript - 使用 jQuery 清除输入字段中的值

javascript - 输入文本框上的正则表达式在 javascript 中不起作用

javascript - 使用 Three.js 在对象上绘画

javascript - 如何使用 HTML5 Canvas 将圆弧转换为直线?

javascript - Kineticjs:应用滤镜后阴影模糊不起作用

javascript - 有条件返回(无 if 或三元)

javascript - 我正在使用 HTML5 Boilerplate,并希望将多个 jQuery 插件合并到一个文件中 : how can this be done?

javascript - 单击选择,添加选项,然后打开选择下拉列表

javascript - 为什么 KineticJS 文档中没有方法 draw()?

Javascript createImageData 抛出 DOM 异常 9,rgb 数据不工作