Canvas draw calls are rendering out of sequence

Posted by Tom Murray on Stack Overflow See other posts from Stack Overflow or by Tom Murray
Published on 2012-06-30T21:11:08Z Indexed on 2012/06/30 21:15 UTC
Read the original article Hit count: 138

Filed under:
|
|
|

I have the following code for writing draw calls to a "back buffer" canvas, then placing those in a main canvas using drawImage. This is for optimization purposes and to ensure all images get placed in sequence.

Before placing the buffer canvas on top of the main one, I'm using fillRect to create a dark-blue background on the main canvas.

However, the blue background is rendering after the sprites. This is unexpected, as I am making its fillRect call first.

Here is my code:

render: function() {
  this.buffer.clearRect(0,0,this.w,this.h);
  this.context.fillStyle = "#000044";
  this.context.fillRect(0,0,this.w,this.h);

  for (var i in this.renderQueue) {
    for (var ii = 0; ii < this.renderQueue[i].length; ii++) {
      sprite = this.renderQueue[i][ii];

      // Draw it!
      this.buffer.fillStyle = "green";
      this.buffer.fillRect(sprite.x, sprite.y, sprite.w, sprite.h);
    }
  }

  this.context.drawImage(this.bufferCanvas,0,0);
}

This also happens when I use fillRect on the buffer canvas, instead of the main one.

Changing the globalCompositeOperation between 'source-over' and 'destination-over' (for both contexts) does nothing to change this.

Paradoxically, if I instead place the blue fillRect inside the nested for loops with the other draw calls, it works as expected...

Thanks in advance!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html5