2013-02-25 26 views
5

come posso modificare il seguente codice in modo che la linea disegnata sia tratteggiata, è possibile vederla in azione nel jfiddle fornito.Animate linea tratteggiata progressivamente disegnata HTML5 Canvas & Jquery

<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/

+0

La [specifica whatwg per canvas] (http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#line-styles) menziona un metodo setLineDash che è supposto per farlo, ma nessun browser che ho provato lo supporta. – Philipp

+0

Vedere [this] (http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas) risposta su come realizzare linee tratteggiate o tratteggiate nella tela. – Zemljoradnik

risposta

5

Use "stroke-dasharray" attributo:

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

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

es:

  canvas.path(subpath).attr({ 
       stroke: colorNumber, 
       "stroke-dasharray":"--" 
      }); 
+0

Grazie, perfetto! Sai come posso adattare il codice così da iniziare con un clic di un link? O qualsiasi altro evento? – user1937021

+0

http://jsfiddle.net/eA8bj/72/ <- Basta usare jQuery su() e utilizzare qualsiasi evento tu voglia utilizzare. – StuR