Skip to main content

Drawing Dashed Lines on an HTML5 Canvas

The canvas element in HTML is great, but has one strange shortcoming: it cannot draw dashed lines (natively). However, dashed lines seem like a pretty common thing to draw, which only highlights the problem.

Looking around, I've noticed several solutions to this problem. Some use trig, and others use their own libraries that must be imported. So in the end, I decided to create my own method.

This code will add the function to all canvas elements, both those already on the page, and any that are dynamically added later.

Here is the code:
CanvasRenderingContext2D.prototype.dashedLine = function(x1, y1, x2, y2, dashLen) {
    if (dashLen == undefined) dashLen = 2;
    this.moveTo(x1, y1);
    var dX = x2 - x1;
    var dY = y2 - y1;
    var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY) / dashLen);
    var dashX = dX / dashes;
    var dashY = dY / dashes;
    var q = 0;
    while (q++ < dashes) {
     x1 += dashX;
     y1 += dashY;
     this[q % 2 == 0 ? 'moveTo' : 'lineTo'](x1, y1);
    this[q % 2 == 0 ? 'moveTo' : 'lineTo'](x2, y2);

To use this, just plop this code into your page, so that it executes before you use it (onload, head, top of body, etc). The method takes 4 or 5 parameters: the start and end coordinate pairs, and (optionally) the dash length. If the dash length is not specified, it will default to 2 pixels. When you need to use it, simply call it on the context object (e.g. context.dashedLine(100, 100, 200, 200, 3);).

Feel free to use this anytime you need it, and let me know in the comments if you like this or if you have a better solution.

P.S. For those worried about size, here is the same code, but minified using the Closure Compiler:
CanvasRenderingContext2D.prototype.dashedLine=function(d,e,g,h,a){if(a==undefined)a=2;this.beginPath();this.moveTo(d,e);var b=g-d,c=h-e;a=Math.floor(Math.sqrt(b*b+c*c)/a);b=b/a;c=c/a;for(var f=0;f++<a;){d+=b;e+=c;this[f%2==0?"moveTo":"lineTo"](d,e)}this[f%2==0?"moveTo":"lineTo"](g,h);this.stroke();this.closePath()};


  1. Hi,
    Thank you for your post, it works for simple dash patterns. In a real world scenarie you though would need a more advanced dash pattern setup.

    One webpage writing about this is:
    In graphics models like Postscript and SVG you use the same model for defining how the pattern should look like (you can see it in the above mentioned webpage). For instance you may define a dash pattern like this:
    var dashPattern = [21, 9, 3, 9]

    Which should be rendered like this:
    "21 units of painted, 9 left blank, 3 painted, 9 left blank" and starting over again.

    At one time before HTML5 and Canvas I tried to implement an online dash pattern generater with preview. The webapp should help create custom dash pattern in postscript (Actually the Adobe Illustrator variant .ai) so that users of a vector drawing package Xara Designer Pro 7 (current version: could get custom dash patterns.

    With the arrival of HTML5 Canvas I want to improve the online preview of the dash pattern people design, and found your page... However I need to be able to draw using the postscript/.ai dash pattern style. Do you think that you can do that? Make a new version which can handle that? I would love it! :-)

    My old (actually not working...) dash pattern generator can be found here:


  2. Very nice! Worked perfectly for me, thanks!

    If you want to see the results it's here:

  3. works perfectly. thanks. do u have a similar solution for drawing parallel and perpendicular lines?

  4. i would suggest to add color also :)
    add var color

    CanvasRenderingContext2D.prototype.dashedLine = function(x1, y1, x2, y2, dashLen, color)
    if (color == undefined) color = "#000";
    this.strokeStyle = color

    thats all now u can use it like:
    context.dashedLine(250, 250, 250, 0, 3, "#fff");

    hope its usefull

  5. Thanks, it worked for me, with a few changes though. I found a way to draw dashed lines in firefox and IE on canvas , thanks a lot :)

  6. Casino online games -
    Discover the casino games that are available to play. Games, 토토사이트 such as jackpot slots, roulette, blackjack, and 카지노사이트 live dealer, have gained a lot of attention and recognition


Post a Comment

Popular posts from this blog

Linux on XPS 15 9550/9560 with TB16 Dock [Update:3/29]

Finally got a laptop to replace my fat tower at work - Dell XPS 15 9560. I was allowed to choose which one I wanted and chose the XPS for its Linux support since Dell ships developer edition XPS's running Ubuntu so I figured Linux support would be better than other manufacturers. At first they got me the model with the 4K screen but my monitors are 2K and multi-dpi support in Linux is virtually non-existent and even hi-dpi support on its own is pretty terrible. So I got it exchanged for the model with the regular 1080p screen (which happened to also be the updated 9560 model), which works much better. I'm very glad to report that pretty much everything works, including the TB16 desktop dock, with just a bit of settings tweaking. This post is to help anybody considering getting this setup or looking for help getting things working. For now, I am running Kubuntu 16.04 with KDE Neon installed. List of things I explicitly tested and work: WiFi, Bluetooth Thunderbolt charging

My Views on Code Indentation

I have read many, many articles about the whole tab vs. space indentation thing. Personally, I don't necessarily agree with most of them. They will require the coder to use a specific indentation size and stick with it, even forcing that on other coders. First off, let me outline my method for indenting code. Then I will explain the reasons and advantages/disadvantages. When I indent code, I will use tabs, but only at the beginning of a line. To align something in the rest of the line, I will use spaces. If a line spills to the next line(s), I will indent that line two tabs further. Rationale: Tabs Why tabs? First off, they're compact in the file (1 byte each). This is really insignificant with current disk sizes, but still. If you indent in spaces, then your file will be larger (unless you indent with one space). Another advantage of tabs is that a tab is a tab. It doesn't specify by how many spaces the code is indented, but rather by how many tabs it is indente

Generating PDFs in Rails with Prawn and Prawnto

There are several different PDF generation libraries available for Rails apps. Some of these are PDF::Writer, Prawn, Ruport, RGhost, and FlyingSaucer (for JRuby). First off, Ruport is basically a higher-level API for PDF::Writer. FlyingSaucer is only for JRuby (because JRuby allows for loading of Java classes). Not having any experience with RGhost, I can't exactly write a guide for using it. So now it's basically between Prawn and PDF::Writer, unless there's another library I haven't hear of. However, to my dismay, there is not UTF-8 support in PDF::Writer. So Prawn ends up being the PDF generation library of choice. One thing to keep in mind is that Prawn and Prawnto are beta-stage (sometimes even alpha) libraries, so some code hacking is going to be necessary. Also note the Prawnto is not maintained or tested by the Prawn developers, so there's no guarantee that it'll work with future versions (especially since Prawnto's developer has been "below t