DIV CSS 佈局教程網

只用 jQuery 打造 3D 透視旋轉效果
編輯:JQuery特效代碼     

不使用 WebGL、不使用 canvas,純粹靠 div 的絕對定位與縮放,也能做出具有透視感的 3D 旋轉動畫。原理其實不複雜:物體離 viewer 越遠,投影就越小、越靠近中心。

透視公式

整個效果建立在最前面那個 _set3d 方法上:

var zomx = fl / (fl + this.z());     // 依 z 值算出縮放比例
var x = this.vx + zomx * this.x();   // 投影後的螢幕座標
var y = this.vy + zomx * this.y();

fl 是焦距(focal length),z 是該物體的縱深。z 越大代表越遠,分母變大、比例變小,於是圖形縮小並向中心靠攏——這正是透視的基本規則。vx/vy 則是視窗中心點,作為投影的消失點基準。

完整程式碼

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
.s_c {
  position: relative; width: 800px; height: 300px;
  border: 1px solid #000; overflow: hidden;
}
</style>
<script type="text/javascript">
var Sl = Sl || {};
(function(){
  var undefined;

  // ---- 基礎方塊:管理位置、尺寸、縮放與層級 ----
  function box(o){
    var d = $.extend({}, {
      'w': 40, 'h': 30, 'secne': null, 'data': ''
    }, o);
    if (d.secne == null || !d.secne) return;

    this.div = $("<div></div>").css({
      'position': 'absolute', 'border': '1px solid #cde',
      'left': '0px', 'top': '0px'
    }).html(d.data);

    this.w(d.w);
    this.h(d.h);
    this._ow = this.w();     // 記錄原始寬高,供縮放運算使用
    this._oh = this.h();
    $(d.secne).append(this.div);
    return this;
  }

  box.prototype.zoomw = function(v){
    if (v == undefined) { this._zw = this._zw || 1; return this._zw; }
    this.w(this.ow() * v, false);
    this._zw = v;
    return this;
  };
  box.prototype.zoomh = function(v){
    if (v == undefined) { this._zh = this._zh || 1; return this._zh; }
    this.h(this.oh() * v, false);
    this._zh = v;
    return this;
  };

  // x / y 是中心座標,因此定位時要減去半寬半高
  box.prototype.x = function(x){
    if (x == undefined) { this._x = this._x || 0; return this._x; }
    this.div.css({ left: x - (this.w()) / 2 });
    this._x = x;
    return this;
  };
  box.prototype.y = function(y){
    if (y == undefined) { this._y = this._y || 0; return this._y; }
    this.div.css({ top: y - (this.h()) / 2 });
    this._y = y;
    return this;
  };

  box.prototype.ow = function(){ return this._ow || 0; };
  box.prototype.oh = function(){ return this._oh || 0; };

  box.prototype.w = function(w, rs){
    if (w == undefined) {
      w = this.div.css('width');
      w = w == 'auto' ? this.div.width() : w;
      return parseInt(w);
    }
    if (rs !== false) this._ow = w;
    this.mx(-(w - this.w()) / 2);      // 尺寸變化時同步修正座標,維持中心不動
    this.div.css({ 'width': w });
    return this;
  };
  box.prototype.h = function(h, rs){
    if (h == undefined) {
      h = this.div.css('height');
      h = h == 'auto' ? this.div.height() : h;
      return parseInt(h);
    }
    if (rs !== false) this._oh = h;
    this.my(-(h - this.h()) / 2);
    this.div.css({ 'height': h });
    return this;
  };

  box.prototype.mx = function(x){
    var div = this.div;
    div.css({ 'left': parseInt(div.css('left')) + x });
  };
  box.prototype.my = function(y){
    var div = this.div;
    div.css({ 'top': parseInt(div.css('top')) + y });
  };
  box.prototype.z = function(z){
    if (z == undefined) return this.div.css('z-index');
    this.div.css("z-index", z);
    return this;
  };

  // ---- 3D 方塊:在 box 之上加上透視投影 ----
  function box3d(o){
    if (!$(o.secne)) return;
    var secne = o.secne;
    secne = this.secne = $(secne);
    this.vx = parseInt(secne.css('width')  == 'auto' ? secne.width()  : secne.css('width'))  / 2;
    this.vy = parseInt(secne.css('height') == 'auto' ? secne.height() : secne.css('height')) / 2;
    this.fl = o.fl || 250;             // 焦距
    this.box = new box(o).z(0);
    this._set3d();
    return this;
  }

  box3d.prototype.x = function(x){
    if (x == undefined) return this._x || 0;
    this._x = x || 0; this._set3d(); return this;
  };
  box3d.prototype.y = function(y){
    if (y == undefined) return this._y || 0;
    this._y = y || 0; this._set3d(); return this;
  };
  box3d.prototype.z = function(z){
    if (z == undefined) return this._z || 0;
    this._z = z || 0; this._set3d(); return this;
  };

  box3d.prototype._set3d = function(){
    var boxo = this.box;
    var fl   = this.fl;
    var zomx = fl / (fl + this.z());
    var x = this.vx + zomx * this.x();
    var y = this.vy + zomx * this.y();
    boxo.zoomw(zomx).zoomh(zomx);
    boxo.x(x);
    boxo.y(y);
  };

  // ---- 環形排列的旋轉場景 ----
  function slide(o){
    var d = $.extend({}, { 'z': 100, 'secne': null }, o);
    if (d.secne == null || !$(d.secne)) return;
    this.cecne  = d.secne;
    this.z      = d.z;
    this.sleep  = 0.02;
    this.box    = [];

    var k = { 'secne': d.secne, 'w': 80, 'h': 50, fl: 1000 };
    var c = 8;
    for (var i = 0; i < c; i++) {
      var t = parseInt(i - c / 2);
      var a = $('<div></div>').css({
        width: '100%', height: '100%', background: '#777'
      });
      k.data = a;
      var ubox = new box3d(k).z(300);
      this.r(ubox, t / 2);       // 以 Y 軸旋轉公式配置初始角度
      this.box.push(ubox);
    }
    this.re_index();
  }

  slide.prototype._moveaction = function(){
    var s = this.sleep;
    for (var i = 0; i < this.box.length; i++) {
      this.r(this.box[i], s);
    }
    this.re_index();
  };

  // Y 軸旋轉矩陣
  slide.prototype.r = function(rbox, s){
    if (!(rbox instanceof box3d)) return;
    var X = rbox.x();
    var Y = rbox.y();
    var Z = rbox.z();
    var New_X = X * Math.cos(s) - Z * Math.sin(s);
    var New_Z = X * Math.sin(s) + Z * Math.cos(s);
    var New_Y = Y;
    rbox.x(New_X);
    rbox.y(New_Y);
    rbox.z(New_Z);
  };

  // 依 z 值由遠到近排序,決定 z-index 疊放順序
  slide.prototype.re_index = function(){
    var arr = this.box;
    var s = arr.length;
    for (var j = 0; j < s - 1; j++) {
      for (var i = 0; i < s - j - 1; i++) {
        if (arr[i].z() < arr[i + 1].z()) {
          var c = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = c;
        }
      }
    }
    for (var i = 0; i < arr.length; i++) arr[i].box.z(i);
  };

  slide.prototype.start = function(){ this.run = 1; this._move(); };
  slide.prototype.stop  = function(){ this.run = 0; };

  slide.prototype._move = function(s){
    var _this = this;
    setTimeout(function(){
      if (!_this.run) return;
      _this._moveaction();
      _this._move();
    }, 50);
  };

  Sl.slide = slide;
})();

$(function(){
  var s = new Sl.slide({secne: '.s_c'});
  $('#start').click(function(){ s.start(); });
  $('#stop').click(function(){ s.stop(); });
});
</script>
</head>
<body>
<div class='s_c'></div>
<button id="start">start</button>
<button id="stop">stop</button>
</body>
</html>

三層設計的分工

程式碼分成三層,各司其職。box 負責最基礎的 2D 方塊:位置、尺寸、縮放與層級,並且刻意把「寬高變化時要同步修正座標」這件事藏在 w() 與 h() 裡,讓呼叫端不必操心中心點偏移。box3d 疊在上面,把 3D 座標換算成 2D 投影後再交給 box 渲染。slide 則負責管理多個方塊、套用 Y 軸旋轉矩陣,並在每一幀重新排序 z-index。

其中 re_index 用氣泡排序依 z 值重排,確保離 viewer 近的方塊永遠蓋在遠的上面——這一步是 3D 視覺能否成立的關鍵,少了它畫面就會出現前後錯亂的破綻。

動畫則以 setTimeout 每 50 毫秒推進一格,並用 this.run 旗標控制暫停。若改用 requestAnimationFrame,能與瀏覽器的重繪週期同步,在效能與電池消耗上都會更好。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved