對於我製作的棋盤遊戲,我必須設計一張由六角形瓷磚組成的地圖。地圖的地理位置(森林,山脈等)由瓦片的圖像表示,因此也是如此。我需要從幾張圖像中剪下六角形區域,並一次又一次地使用它們。在開始設計地圖之前,我需要確保每個單獨的瓷磚按預期工作。但是我卡住了。這是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