This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line.
If you want to draw lines having a custom style there is no methos in the API. 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 created using any image. You create image for your custom pattern and set strokeStyle of the context like the following:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.setLineDash([5, 3]);/*Dash width and spaces between dashes.*/
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(400, 100);
ctx.stroke();
If you want to draw lines having a custom style there is no methos in the API. 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 created using any image. You create image for your custom pattern and set strokeStyle of the context like the following:
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.
Comments
Post a Comment