15 November 2010

HTML5 Canvas terribly slow drawing lines [not]

Quick heads-up if your canvas application is running awfully slowly, and you're using beginPath(), moveTo(), and/or lineTo().

A simple interpretation of canvas documentation suggests this is a fine way to draw a series of parallel lines (as one might do if one was for example drawing a background grid on one's canvas) ...


  for (var here = start; here < end; here += interval) {
    cx.beginPath();
    cx.moveTo(here, top);
    cx.lineTo(here, bottom);
    cx.stroke();
  }

One would be terribly, terribly wrong! Well, not wrong exactly, but awfully slow ... try this instead


  cx.beginPath();
  for (var here = start; here < end; here += interval) {
    cx.moveTo(here, top);
    cx.lineTo(here, bottom);
  }
  cx.stroke();

The beginPath() and stroke() calls are only needed once each per refresh. My grid drawing dropped from 40ms to 3ms with this change. Not bad ...