Или вы можете просто использовать массив, содержащий ваши объекты для рисования, а затем отсортировать этот массив, используя свойство zIndex
каждого дочернего элемента.Затем вы выполняете итерацию этого массива и рисуете.
var canvas = document.querySelector('#game-canvas');
var ctx = canvas.getContext('2d');
// Define our shape "class".
var Shape = function (x, y, z, width, height) {
this.x = x;
this.y = y;
this.zIndex = z;
this.width = width;
this.height = height;
};
// Define the shape draw function.
Shape.prototype.draw = function () {
ctx.fillStyle = 'lime';
ctx.fillRect(this.x, this.y, this.width, this.height);
};
// let's store the objects to be drawn.
var objects = [
new Shape(10, 10, 0, 30, 30), // should be drawn first.
new Shape(50, 10, 2, 30, 30), // should be drawn third.
new Shape(90, 10, 1, 30, 30) // should be drawn second.
];
// For performance reasons, we will first map to a temp array, sort and map the temp array to the objects array.
var map = objects.map(function (el, index) {
return { index : index, value : el.zIndex };
});
// Now we need to sort the array by z index.
map.sort(function (a, b) {
return a. value - b.value;
});
// We finaly rebuilt our sorted objects array.
var objectsSorted = map.map(function (el) {
return objects[el.index];
});
// Now that objects are sorted, we can iterate to draw them.
for (var i = 0; i < objectsSorted.length; i++) {
objectsSorted[i].draw();
}
// Enjoy !
Обратите внимание, что я не тестировал этот код и написал его на своем мобильном телефоне, так что могут быть опечатки, но это должно позволить понять принцип, я надеюсь.