【发布时间】:2018-01-11 17:03:13
【问题描述】:
对于我正在制作的棋盘游戏,我必须设计一个由六边形图块组成的地图。地图的地理(森林、山脉等)由图块的图像表示,因此也是如此。我需要从几张图像上剪下一个六边形区域,然后一次又一次地使用它们。在开始设计地图之前,我需要确保每个单独的图块都按预期工作。但是我被卡住了。这是Tile 类的代码
var Tile = function (startX, startY, l, img) {
this.side = l; //length of the hexagon's size
this.startingPoint = [startX, startY];
this.image = img;
this.incrX = Math.sqrt(3)*this.side/2;
this.incrY = this.side/2;
this.points = [
this.startingPoint,
[startX + this.incrX, startY - this.incrY],
[startX + 2*this.incrX, startY],
[startX + 2*this.incrX, startY + this.side],
[startX + this.incrX, startY + this.side + this.incrY],
[startX, startY + this.side]
]; //list of points comprising the path for making the hexagonal tile
this.middlePoint = [startX + this.incrX, startY + this.side/2];
//draws the hexagonal tile
this.show = function (context) {
context.save();
context.beginPath();
context.moveTo(this.startingPoint[0], this.startingPoint[1]); //starting at the starting point (duh)
for(var i=1; i<this.points.length; i++){
context.lineTo(this.points[i][0], this.points[i][1]); //looping through the rest of the points
}
context.closePath(); //closing the path
if(this.image){
context.clip();
context.drawImage(this.image, 50, 20);
}
context.restore();
context.stroke();
}
}
为了测试代码的正确性,我尝试在画布上绘制 2 个图块:
var context = document.getElementById("canvas").getContext('2d');
context.canvas.height = window.innerHeight;
context.canvas.width = window.innerWidth;
var img = new Image;
img.onload = function () {
var tile = new Tile(200, 100, 50, img);
var tile2 = new Tile(200, 400, 50, img);
tile.show(context);
tile2.show(context);
}
img.src = "tree.png";
绘制了 2 个图块,但实际上只有其中一个被图像填充。除此之外,我觉得这段代码效率很低。我不得不使用的context.save() 方法是一项昂贵的操作,并且需要绘制数百个图块会带来一些性能问题。我这样做对吗?设计Tile 类以避免性能问题的更有效方法是什么?
【问题讨论】:
-
目前,图像是使用将要绘制的坐标进行裁剪的——因此,图块只会显示位于图块所在位置下方的全屏图像部分——没有图块是相同的。这可以解释为什么只有一个图块出现。我的问题是,您是否打算让磁贴具有将一遍又一遍地重复的固定内容?
-
@Traktor53 是的,应该修复内容。可能会有 4-5 种不同类型的图块,但相同类型的图块的外观和行为应该完全相同。
标签: javascript html image canvas