2013-02-25 97 views
5

如何修改下面的代碼,以便繪製的線條是虛線,您可以在提供的jfiddle中看到它的操作。動畫逐步繪製虛線HTML5畫布和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

[whatwg規範的畫布](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#line-styles)提到了一個setLineDash方法要做到這一點,但沒有我嘗試過的瀏覽器支持。 – Philipp 2013-02-25 12:03:29

+0

請參閱[this](http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas)回答如何在畫布中製作虛線或虛線。 – Zemljoradnik 2013-02-25 12:20:08

回答

5

使用 「行程dasharray」 屬性:

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":"--" 
      }); 
+0

謝謝,完美!你知道我可以如何調整代碼,以便點擊鏈接啓動它?或者任何其他事件? – user1937021 2013-02-25 14:57:43

+0

http://jsfiddle.net/eA8bj/72/ < - 只需在()上使用jQuery,並使用您想要使用的任何事件。 – StuR 2013-02-25 15:09:00