对于我制作的棋盘游戏,我必须设计一张由六角形瓷砖组成的地图。地图的地理位置(森林,山脉等)由瓦片的图像表示,因此也是如此。我需要从几张图像中剪下六角形区域,并一次又一次地使用它们。在开始设计地图之前,我需要确保每个单独的瓷砖按预期工作。但是我卡住了。这是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
@ Traktor53是的内容应该是固定的。可能会有4-5种不同类型的瓷砖,但相同类型的瓷砖应该看起来和行为完全相同。 – VlassisFo