title: Javascript rendering to HTML canvas extremely slowly
body: <p>I am trying to render a grid to an HTML canvas by rendering individual squares (because later on the cells should not all look the same but have individual behaviors).</p>
  
  <p>I have created a minimal example which shows the performance issues I am having. Running this script nearly freezes my browser, until it offers to stop the script for me because it's detecting that this script is running too slowly.</p>
  
  <p>I have a similar example running the Javascript framework p5.js and it's running fine in terms of performance.
  However, I want to move to basic Javascript without that framework.</p>
  
  <p>Here's the minimal example causing the performance issues. I'd be happy about any suggestions why this might run so slowly...</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>const canvas = document.getElementById('canvas');
  const context = canvas.getContext('2d');
  const width = canvas.width;
  const height = canvas.height;
  
  let grid_width = 50;
  let grid_height = grid_width;
  let grid = [];
  
  class Cell {
    constructor(i,j) {
      this.i = i;
      this.j = j;
      this.width = width / grid_width;
      this.height = height / grid_height;
      this.x = i*this.width;
      this.y = j*this.height;
    }
  
    render(color) {
      context.rect(this.x, this.y, this.width, this.height);
      context.strokeStyle = '#000000';
      context.lineWidth = .25;
      if(color) {
        context.fillStyle = color;
      }
      context.fillStyle = '#FFFFFF';
      context.fill();
      context.stroke();
    }
  }
  
  for(let i = 0; i &lt;= grid_width; i++) {
    if(!(grid[i])) {
      grid[i] = [];
    }
    for(let j = 0; j &lt;= grid_height; j++) {
      grid[i][j] = new Cell(i, j);
    }
  }
  
  function draw() {
    context.clearRect(0, 0, width, height);
    grid.forEach(row =&gt; {
      row.forEach(cell =&gt; {
        cell.render();
      });
    });
    requestAnimationFrame(draw);
  }
  
  // This call to draw will run very slowly!
  // draw();</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;head&gt;
      &lt;!-- &lt;script src="p5.js"&gt;&lt;/script&gt; --&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;canvas id="canvas" width="800" height="800"&gt;&lt;/canvas&gt;&lt;br&gt;
      &lt;script src="sketch.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Please note that I have commented out the call to draw() because my script also wrecks the "Run code snippet" button on this site...</p>