title: Javascript Canvas Draw Order
body: <p>I am plotting a bar chart with some series values in a javascript loop. Even though the code drawing the series values lies below the code that draws the bars, in the next iteration of the loop the text that has just been drawn gets overwritten. </p>
  
  <p>You can see this effect taking place in the code below as the alert boxes appear.</p>
  
  <p>Why do drawing operations on another part of the canvas overwrite something drawn previously in a completely different place?</p>
  
  <p><em>Update:</em> Someone has helpfully pointed out that using <code>fillRect()</code> hides this issue, but my question is rather: why is it happening in the first place?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var exampleData = {
    "Series 1": 10,
    "Series 2": 14,
    "Series 3": 2,
    "Series 4": 12
  };
  
  var BarChart = function(options) {
    this.options = options;
    this.canvas = options.canvas;
    this.ctx = this.canvas.getContext("2d");
    this.colors = options.colors;
  
    this.plot = function() {
      var maxValue = 0;
      for (var categ in this.options.data) {
        maxValue = Math.max(maxValue, this.options.data[categ]);
      }
  
      var noBars = Object.keys(this.options.data).length;
      var barWidth = (this.canvas.height) / noBars;
      var barIdx = 0;
  
      for (categ in this.options.data) {
        var barLength = Math.round(this.canvas.width * this.options.data[categ] / maxValue);
        this.ctx.save();
        alert("plotting series line " + categ);
        this.ctx.fillStyle = this.colors[barIdx % this.colors.length];
        this.ctx.rect(30, barIdx * barWidth, barLength, barWidth);
        this.ctx.fill();
        alert("plotting series value " + categ);
        this.ctx.fillStyle = "#000000";
        this.ctx.font = "24px Georgia";
        this.ctx.textBaseline = "middle";
        this.ctx.fillText(this.options.data[categ], 25, barIdx * barWidth + barWidth / 2); //will be covered in the loop's next iteration. Why?
        this.ctx.restore();
        barIdx++;
      }
    }
  }
  
  function init() {
    var myCanvas = document.getElementById("myCanvas");
    myCanvas.width = 800;
    myCanvas.height = 300;
    var ctx = myCanvas.getContext("2d");
    var myBarChart = new BarChart({
      canvas: myCanvas,
      seriesName: "Example Series",
      padding: 40,
      data: exampleData,
      colors: ["#D1E3F3", "#D1E3F3", "#D1E3F3", "#D1E3F3"]
    });
    myBarChart.plot();
  }
  document.addEventListener("DOMContentLoaded", init, false);</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="myCanvas"&gt;&lt;/canvas&gt;</code></pre>
  </div>
  </div>
  </p>