iconfu iconfu iconfu is the world's largest collection of free, open-source icons and it comes with a handy image editor, so you can tweak icons to suit your needs exactly or even draw your own from scratch
invert blue resize move up verbose drawmode lighter previews remove swap animator library library draw shift up make a copy large editor explorer your icon contract agreement tag

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 ...