JavaScript - 拆分要存储在2D Image()数组中的tileset图像 [英] JavaScript - Splitting a tileset image to be stored in 2D Image() array
问题描述
假设我有这张图片:
我有这个2D数组 tiles []
..并使用 Image()
function ...怎样才能使用(我认为最好的方法?) for
loop来添加每个tile进入数组
所以 tile [0]
通过许多读取并用作 Image()
稍后要在HTML5画布上绘制对象?
and I have this 2D array tiles[]
.. and using Image()
function... how can do I use the (what I assume be best way?) for
loop to add each tile into the array
so tile[0]
through however many there are is read and used as Image()
objects later to be painted on HTML5 canvas?
推荐答案
我会...
- 计算这个图像宽和高的图块数
- 将图像绘制到内存中的画布上,并使用上下文来获取图像数据。
- 循环并对每个图块进行子图像处理,存储在数组中。
假设:
imageWidth,imageHeight,tileWidth,tileHeight
imageWidth, imageHeight, tileWidth, tileHeight
所有描述他们的na mes建议,并且:
All describe what their names suggest, and:
编辑:根据评论添加图片加载,错误地修复名称 ImageWidth
和 ImageHeight
至 imageWidth
和 imageHeight
Added image load as per comment, fixed wrongly name ImageWidth
and ImageHeight
to imageWidth
and imageHeight
编辑:在此处绘制图像时,在 imageObj.onload
内执行代码,从原点绘制drawImage() 0,0)
Performing code inside imageObj.onload
as the image is drawn here, drawImage() from origin (0,0)
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "tilesetImageLocationHere";
imageObj.onload = function() {
ctx.drawImage(imageObj, 0, 0);
然后,将图像拆分为图块数据列表..
Then, split up your image into a list of tile data..
var tilesX = imageWidth / tileWidth;
var tilesY = imageHeight / tileHeight;
var totalTiles = tilesX * tilesY;
var tileData = new Array();
for(var i=0; i<tilesY; i++)
{
for(var j=0; j<tilesX; j++)
{
// Store the image data of each tile in the array.
tileData.push(ctx.getImageData(j*tileWidth, i*tileHeight, tileWidth, tileHeight));
}
}
//From here you should be able to draw your images back into a canvas like so:
ctx.putImageData(tileData[0], x, y);
}
这篇关于JavaScript - 拆分要存储在2D Image()数组中的tileset图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!