HTML5 Canvas set z-index

后端 未结 5 1267
陌清茗
陌清茗 2020-12-01 07:48

Is it possible to set the z-index of a drawn object in HTML5 canvas?

I am trying to get it so one object can be infront of a the \"player\" and another object is beh

5条回答
  •  日久生厌
    2020-12-01 08:17

    Or you could simply use an array containing your objects to be drawn then sort this array using the zIndex property of each child. Then you jist iterate that array and draw.

    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 !
    

    Note that I didnt tested that code and wrote it on my cellphone, so there might be typos, but that should permits to understand the principle, i hope.

提交回复
热议问题