以前在CodePen上接觸了TweenMax, 被它能作到的酷炫效果震撼了. (文末放了5個GSAP的效果GIF)css
最近要作一個"收集水滴"的動效, 因而就試用了一下TweenMax實現這個效果.web
TweenMax是GSAP(GreenSock Animation Platform)創做的動畫工具庫. GSAP的產品除了TweenMax, 還有:chrome
TweenMax就是GSAP的"全家桶", 包含了TweenLite, TimelineLite, TimelineMax, CSSPlugin, AttrPlugin, RoundPropsPlugin, DirectionalRotationPlugin, BezierPlugin 和 EasePack.app
想起步, 先看看這個Get Started裏的視頻就行了.工具
最簡單的用法就是TweenMax.to(element, duration, options);
, 例如測試
TweenMax.to('.drop', 3, { x: 100, scale: 2, backgroundColor: #aaa })
可讓.drop
元素在3秒內, 水平移動100px, 放大一倍, 背景色變爲#aaa
.動畫
<!-- jade --> .container .drop .tank
HTML很簡單, 就是.container
裏面一個.drop
一個.tank
.spa
如下JS讓.drop
飄起來飛向.tank
.插件
var collectDrop = function() { var $drop = $('.drop:not(.anim)'), $tank = $('.tank'), from = $drop.position(), to = $tank.position(), // 計算從水滴中心到水缸中心所須要的偏移量. x = to.left - from.left + ($tank.width() - $drop.width()) / 2, y = to.top - from.top + ($tank.height() - $drop.height()) / 2, // 建立動畫用水滴 $el = $drop.clone().addClass('anim').appendTo('.container'), tl = new TimelineMax(); // 水滴升起 tl.to($el, 2, { y: -$el.height() * 3, scale: 2, ease: Elastic.easeOut.config(1, 0.4) }) // 水滴飛向水缸 .to($el, .5, { x: x, y: y, backgroundColor: '#832fc2', scale: .5, ease: Power1.easeIn, onComplete: function() { $el.remove(); } }) // 水缸動效 .to($tank, .1, { scale: 1.3 }) .to($tank, .1, { scale: .8 }) .to($tank, .1, { scale: 1 }); };
這裏爲了實現一連串動畫, 因此使用了TimelineMax. 因爲script
中引入了TweenMax, 因此TimelineMax也就自動被引入了.code
CodePen以下, 你只要點擊水滴就能夠看到收集效果了.
See the Pen tweenmax collect drop by Richard Liu (@lzl124631x) on CodePen.
上面的代碼中關於動效的選項, 用到了x
和y
以利用transform
變換位置, scale
改變大小, backgroundColor
修改顏色, onComplete
爲動畫完成時的callback, ease
設置動畫的easing效果.
在GSAP Ease Visualizer中能夠看到更多的easing效果, 你還能夠在這裏修改參數, 查看效果, 而後將滿意的代碼複製出來.
題外話, 原本只是作個動效, 元素的外觀是次要的. 不過好奇能不能直接用CSS作出水滴效果, 就搜了一下"droplet css", 居然真有這麼作的. 其實原理不難(可就是想不到啊=,.=), 就是利用border-radius
生成一個斜着的水滴, 而後旋轉45度.
.droplet { width: 4em; height: 4em; border-radius: 80% 0 55% 50% / 55% 0 80% 50%; background-color: #07C; transform: rotate(-45deg); }
效果以下:
旋轉45度後⟹
enjoycss.com上還有很多有意思的實現, 好比愛心.
(不過剛發現enjoycss.com仍是alpha版本, 不少bug...好比這個愛心點進去看到的css就是有問題的)
我在這個愛心css的基礎上加了個CSS動效, 讓心臟活了起來, CodePen.
細心的人應該注意到了, 我上面的效果圖中, 水滴在放大以後有比較明顯的毛邊. 我測試了下, 一旦動畫中止, 毛邊就消失了.
針對這個問題搜了一下, CodePen上有一個解決方案.
它的解決方法是: 假設動畫中最大的放大比例是2倍, 那麼一開始繪製元素的時候就用2倍的大小去繪製, 初始使用transform: scale(.5)
縮小到正常比例, 而後動畫放大的時候用scale(1)
.
我試了一下, 的確管用. 更新後的CodePen以下:
See the Pen tweenmax collect drop by Richard Liu (@lzl124631x) on CodePen.
效果圖以下:
可是這個方法不夠優雅, 因而繼續搜了搜, 好比這個SO問題. 但是我試遍了文中講的方法, 包括translateZ(0)
, -webkit-backface-visibility: hidden;
, filter: blur(0);
, 惋惜都無論用(T_T).
請大神出手.
附上幾個GSAP的酷炫CodePen, 你們感覺下, CodePen上搜索GSAP或TweenMax還有不少.