I have made a bezier curve using html5 canvas and I'm wondering if it's possible to make it dashed? My code is:
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d")
ctx.lineWidth = 2;
ctx.strokeStyle = "#fff";
ctx.beginPath();
ctx.moveTo(-200, 350);
ctx.bezierCurveTo(199, 604, 220, 180, 500, 350);
ctx.stroke();
I have created a jsfiddle here
This is the first time I'm using html5 canvas so my skills with it aren't that great at this point. Thanks in advance.
For Chrome you can use:
context.setLineDash([2,3,...]); //pattern, can be more than 2 entries
context.lineDashOffset(0); //start point (ie. walking ants)
context.getLineDash();
For Firefox you can use:
context.mozDash = [2,3,...]; //prefixed for Mozilla at this time
context.mozDashOffset = 0;
A generic function:
function setDash(context, array, offset) {
offset = (typeof offset === 'number') ? offset : 0;
if (typeof context.setLineDash === 'undefined') { //Firefox
context.mozDash = array;
context.mozDashOffset = offset;
}
else { //Chrome
context.setLineDash(array);
context.lineDashOffset = offset
}
}
Walking ants demo (from the archive - works in both Firefox and Chrome):
http://jsfiddle.net/AbdiasSoftware/Mnc94/
Since January 2013, you can do this in Chrome with ctx.setLineDash([2,3]);
where 2 is the stroke in pixels and 3 is the space in pixels.
However other browsers does not implement this yet (Firefox, IE10, Safari, Opera). This is a future simplification not yet in place. Mozilla has an experimental version mozDash
but I have not tested that.
I recommend you implement a check around this, so if this method exists the line appears dashed, otherwise not - but that is assuming that a line is better than no line. The alternative is to implement your own curve drawing of this by calculating arc lengths and turning on and off stroke. See answer here for that: Dashed Curves on Html5 Canvas Bezier