5

how can I modify the following code so that the line drawn is dashed, you can see it in action in the jfiddle provided.

<html>
    <style>
        #canvas
        {
        border-style:solid;
        border-width:1px;
        }
    </style>
    <div id="canvas"> 
        <p>Hover over me</p>        
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</html>

$(function() {

    animateLine = function(canvas, hoverDivName, colorNumber, pathString) {
        $('#' + hoverDivName).hover(

        function() {
            var line = canvas.path(pathString).attr({
                stroke: colorNumber
            });
            var length = line.getTotalLength();

            $('path[fill*="none"]').animate({
                'to': 1
            }, {
                duration: 5000,
                step: function(pos, fx) {
                    var offset = length * fx.pos;
                    var subpath = line.getSubpath(0, offset);
                    canvas.clear();
                    canvas.path(subpath).attr({
                        stroke: colorNumber
                    });

                },
            });
        }, function() {
            $('path[fill*="none"]').stop(true, false).fadeOut();
        });
    };

    var canvas = Raphael('canvas', 200, 200);
    var pathString = "M10 10L10 200L100 200Z";

    animateLine(canvas, "canvas", "#000", pathString);

});

http://jsfiddle.net/eA8bj/

user1937021
  • 10,151
  • 22
  • 81
  • 143
  • The [whatwg specification for canvas](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#line-styles) mentions a setLineDash method which is supposed to do that, but no browser I tried supports that. – Philipp Feb 25 '13 at 12:03
  • See [this](http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas) answer on how to make dashed or dotted line in canvas. – Zemljoradnik Feb 25 '13 at 12:20

1 Answers1

6

Use "stroke-dasharray" attribute:

http://jsfiddle.net/eA8bj/70/

https://developer.mozilla.org/en-US/docs/SVG/Attribute/stroke-dasharray

e.g:

            canvas.path(subpath).attr({
                stroke: colorNumber,
                "stroke-dasharray":"--"
            });
StuR
  • 12,042
  • 9
  • 45
  • 66
  • Thanks, perfect! Do you know how I ca adapt the code so it initiates on a a click of a link? Or any other event? – user1937021 Feb 25 '13 at 14:57
  • http://jsfiddle.net/eA8bj/72/ <-- Just use jQuery on(), and use whichever event you want to use. – StuR Feb 25 '13 at 15:09