Thursday, November 4, 2010

Html5 Canvas Drawing -- Draw dotted or dashed line





This post is for those who want to use html5 canvas for drawing. Canvas have methods to draw lines of different widths but not for different styles. Like if you want to draw dotted lines or dashed line there is no such stroke style. But fortunately there is a way to achieve this. Following is a description about how I achieved this.

You can set the stroke pattern on canvas context. Stroke pattern can be any canvas pattern. So here I created an image of 1 pixel height and 6 pixel width. First three pixels were black and other three were white. Now I created the image to create a repeating pattern.

       var linePattern;
       imageToUsedAsPattern.onload = function() {
               linePattern = context.createPattern(
imageToUsedAsPattern, "repeat");
               context.strokeStyle=linePattern;
        }
        var imageToUsedAsPattern = new Image();

        imageToUsedAsPattern.src = "images/linePatterns.jpg";    

Now all the calls to context.stroke will use the pattern to draw strokes. Like if you create a line from the top left corner of the canvas to the bottom right corner it will be a dashed line.

         context.moveTo(0,0);
         context.lineTo(canvas.width,canvas.height);
         context.stroke();


You can achieve dotted line in similar way by creating an image may be two pixel wide. First pixel of white color and second of black color.


A limitation of this is that you can create lines of only white and black color or only of those colors for which you have already created the images. To provide lines of any color you may create another image on the fly using canvas element and doing pixel mainpulation.

3 comments: