假设我有这张图片:
我有这个2D数组tiles[]
..并使用Image()
函数...如何使用(我认为最好的方法?)for
循环来添加每个tile都放入array
所以tile[0]
,然后有很多内容被读取并用作Image()
对象以后要在HTML5画布上绘制?
答案 0 :(得分:4)
我会......
假设:
imageWidth,imageHeight,tileWidth,tileHeight
所有描述他们的名字的建议,并且:
编辑:根据评论添加了图片加载,错误地将名称ImageWidth
和ImageHeight
错误地修改为imageWidth
和imageHeight
编辑:在此处绘制图像时在imageObj.onload
内执行代码,从原点(0,0)执行drawImage()
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);
然后,将您的图像拆分为图块数据列表..
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);
}
答案 1 :(得分:0)
好吧我在我的localhost上做了这个:它应该至少给你一个基础。我认为你应该可以直接使用这个盒子,但你可能需要根据你的需要对它进行一些计算调整。我根本不认为有必要花时间将它完美化为你的榜样:
您显然必须将图像指向您自己的图像。
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var canvas = document.getElementById('fakeCanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = '/theImage.png';
var tiles = [];
var imageTileNumWidth = 23;
var imageTileNumHeight = 21;
img.onload = function(){
var imageWidth = img.width;
var imageHeight = img.height;
sndCanvasWidth = imageWidth/imageTileNumWidth;
sndCanvasHeight = imageHeight/imageTileNumHeight;
canvas.width = imageWidth;
canvas.height = imageHeight;
ctx.drawImage(img,0,0,imageWidth,imageHeight);
var sndCanvas = document.getElementById('drawCanvas');
sndCanvas.width=sndCanvasWidth;
sndCanvas.height=sndCanvasHeight;
var i=0;
var j=0;
var t=0;
for(i=0;i<imageWidth;i+=sndCanvasWidth){
for(j=0;j<imageHeight;j+=sndCanvasHeight){
var myImageData = ctx.getImageData(j,i,sndCanvasWidth,sndCanvasHeight);
var ctx2 = sndCanvas.getContext("2d");
ctx2.putImageData(myImageData,0,0);
tiles.push(myImageData);
}
}
};
});
</script>
</head>
<body>
<canvas id="fakeCanvas"></canvas>
<canvas id="drawCanvas"></canvas>
</body>
</html>