2012-11-12 67 views
3

我用javascript和Raphael構建了一種JavaScript地圖。 我可以在單擊時放大對象,但我希望它可以動畫(如慢慢潛入等)。有沒有辦法做到這一點,而不是重新發明輪子?raphael viewbox動畫縮放

+1

看到類似的問題:http://stackoverflow.com/questions/7736690/raphael-paper-zoom-animation –

+0

我的意思是「animate(...)」,所以我可以做的不僅僅是平滑放大。 –

+0

我認爲你應該回頭再看看Joan的鏈接 - @patrics的回答(如果你問我,這也是值得接受的),你會發現你正在尋找的東西。添加緩動功能也將非常簡單... –

回答

6

沒有理由說svg對象的viewbox不能動畫 - Raphael根本不提供這種功能。然而,創建一個插件相當簡單。例如:

Raphael.fn.animateViewBox = function animateViewBox(x, y, w, h, duration, easing_function, callback) 
{ 
    var cx = this._viewBox ? this._viewBox[0] : 0, 
     dx = x - cx, 
     cy = this._viewBox ? this._viewBox[1] : 0, 
     dy = y - cy, 
     cw = this._viewBox ? this._viewBox[2] : this.width, 
     dw = w - cw, 
     ch = this._viewBox ? this._viewBox[3] : this.height, 
     dh = h - ch, 
     self = this;; 
    easing_function = easing_function || "linear"; 

    var interval = 25; 
    var steps = duration/interval; 
    var current_step = 0; 
    var easing_formula = Raphael.easing_formulas[easing_function]; 

    var intervalID = setInterval(function() 
     { 
      var ratio = current_step/steps; 
      self.setViewBox(cx + dx * easing_formula(ratio), 
          cy + dy * easing_formula(ratio), 
          cw + dw * easing_formula(ratio), 
          ch + dh * easing_formula(ratio), false); 
      if (current_step++ >= steps) 
      { 
       clearInterval(intervalID); 
       callback && callback(); 
      } 
     }, interval); 
} 

安裝此插件後,可以在同一個方法拉斐爾的內置動畫的方法的工作原理使用animateViewBox實例化的任何文件。例如...

var paper = Raphael(0, 0, 640, 480); 
paper.animateViewBox(100, 100, 320, 240, 5000, '<>', function() 
    { 
     alert("View box updated! What's next?"); 
    }); 

示範上演here

+0

輝煌!但現在我遇到了一個新問題。 –

+0

我很高興看到新問題很容易解決! –

0

Raphael動畫通過動畫元素屬性進行工作。當你調用element.animate時,你提供了最終的對象參數,到達那裏的時間以及如果你不希望它是線性的可能的緩動函數。

例如,規模上/下一個圈,你可能會考慮這個例子:http://jsfiddle.net/eUfCg/

// Creates canvas 320 × 200 at 10, 50 
var paper = Raphael(10, 50, 320, 200); 

// Creates circle at x = 50, y = 40, with radius 10 
var circle = paper.circle(50, 40, 10); 
// Sets the fill attribute of the circle to red (#f00) 
circle.attr("fill", "#f00"); 

// Sets the stroke attribute of the circle to white 
circle.attr("stroke", "#fff"); 


var zoomed = false; 

circle.click(function() { 
    if (zoomed) { 
     this.animate({ transform: "s1" }, 500); 
     zoomed = false; 
    } else { 
     this.animate({ transform: "s4" }, 500); 
     zoomed = true; 
    } 
});​ 

哪個動畫圓的變換屬性。要縮放地圖,您應該將所有元素放入組中,並根據要結束的縮放比例和翻譯來爲組的transform屬性設置動畫效果。

有關transform屬性的更多信息,請參閱http://raphaeljs.com/reference.html#Element.transform

+0

這對於一個對象只能工作,對於多個對象,它們只會增長,但不會移動。 –

+0

使用paper.set()將所有內容放入一個集合中並縮放集合。所以是的,它只適用於一個對象,但可以將所有對象組合成一個對象。 –

+0

另外還有許多實現動畫視框https://groups.google.com/forum/?fromgroups=#!topic/raphaeljs/7eA9xq4enDo –