How to Draw Dashed Lines in Canvas

(I could finally finish this draft, after 4 months -_-)

I’m a fun of JavaScript Canvas but I couldn’t believe it doesn’t support drawing dashed lines when this requirement occurs to me. After some investigating I found a good summary about why/how it doesn’t support dashed lines.

What I actually do with canvas is to draw data chart, with a cool JS library named Flot. The reason I need dashed lines is that someone (chuckle) is color-blind so he couldn’t tell the colored lines apart.

One day I decided to have a look at how Flash handles this. To my surprise, Flash doesn’t support dashed lines “natively”, either. So maybe Canvas doesn’t support that for the same reason? However, flash uses an elegant “external” way to draw dashed lines, here is the explanation/demo/code snippet about it.

The ActionScript codes for drawing dashed lines are not hard to understand, so I ported them to JS, or rather, to Flot. Demo. However it isn’t perfect, firstly it’s too slow on IE7 (maybe because of excanvas is not efficient enough?), secondly I didn’t find a good way to draw proper legends for Flot. See Issue 61 of Flot for detail and implementation in patch file.

At least, we can draw dashed lines in Canvas, in the same way as in Flash. Just the performance of IE7 sucks….

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.