製做圖片傾斜(tilt)效果

原文來自:git

http://tympanus.net/codrops/2015/05/28/image-tilt-effect/github

所謂的傾斜效果,我也不知如何用語言描述,那就直接看Demo啦,下面咱們會對這個效果的實現原理逐步分析:
http://codepen.io/CodingMonkeyzh/pen/jPYNyrweb

文檔結構

對一個圖片添加該效果,首先,咱們須要一個具備寬高的容器。DOM 結構很是簡單。app

<div class="container">
  <img class="tilt-effect" src="http://placehold.it/500x300" alt="" />
</div>

上面這段結構通過腳本處理以後,會被替換成下面的結構:函數

<div class="container">
  <div class="tilt">
    <div class="tilt__back" style="background-image: url(http://placehold.it/500x300);"></div>
    <div class="tilt__front" style="opacity: 0.7; -webkit-transform: perspective(1000px) translate3d(0px, 0px, 0px) rotate3d(1, 1, 1, 0deg); transform: perspective(1000px) translate3d(0px, 0px, 0px) rotate3d(1, 1, 1, 0deg); background-image: url(http://placehold.it/500x300);"></div>
    <div class="tilt__front" style="opacity: 0.7; -webkit-transform: perspective(1000px) translate3d(0px, 0px, 0px) rotate3d(1, 1, 1, 0deg); transform: perspective(1000px) translate3d(0px, 0px, 0px) rotate3d(1, 1, 1, 0deg); background-image: url(http://placehold.it/500x300);"></div>
  </div>
</div>

腳本分析

咱們利用了filtfx.js這個插件對上面的圖片進行處理, 來實現傾斜效果。我在原來的代碼中加入了一些註釋,來幫助咱們理解。下面咱們對該插件的核心代碼進行分析。this

function TiltFx(el, options) {
  this.el = el;
  this.options = extend({}, this.options);
  extend(this.options, options);
  this._init();
  this._initEvents();
}

這是構造函數,若是咱們的文檔中,加入了上面的插件,那麼插件會遍歷文檔中具備tilt-effetimg元素,來調用構造函數TiltFx()url

function init() {
  // 遍歷全部擁有‘title-effect’類的img元素
  [].slice.call(document.querySelectorAll('img.tilt-effect')).forEach(function(img) {
    new TiltFx(img, JSON.parse(img.getAttribute('data-tilt-options')));
  });
}

TiltFx()具備一個原型屬性,兩個原型方法。原型屬性配置了一些默認的參數用於調用:.net

/**
 * 默認參數
 */
TiltFx.prototype.options = {
  extraImgs: 2, // 額外的輔助圖片數量
  opacity: 0.7,
  bgfixed: true, // 底圖是否固定
  movement: {    // 這是一些用於移動的參數
    perspective: 1000,
    translateX: -10,
    translateY: -10, 
    translateZ: 20,
    rotateX: 2,
    rotateY: 2,
    rotateZ: 0
  }
}

第一個原型方法是_init(),用於初始化DOM結點,生成咱們的目標DOM結點:prototype

TiltFx.prototype._init = function() {
  this.tiltWrapper = document.createElement('div');
  this.tiltWrapper.className = 'tilt';

  // main image element.
  this.tiltImgBack = document.createElement('div');
  this.tiltImgBack.className = 'tilt__back';
  this.tiltImgBack.style.backgroundImage = 'url(' + this.el.src + ')';
  this.tiltWrapper.appendChild(this.tiltImgBack);

  // image elements limit.
  if (this.options.extraImgs < 1) {
    this.options.extraImgs = 1;
  } else if (this.options.extraImgs > 5) {
    this.options.extraImgs = 5;
  }

  if (!this.options.movement.perspective) {
    this.options.movement.perspective = 0;
  }

  // add the extra image elements.
  this.imgElems = [];
  for (var i = 0; i < this.options.extraImgs; ++i) {
    var el = document.createElement('div');
    el.className = 'tilt__front';
    el.style.backgroundImage = 'url(' + this.el.src + ')';
    el.style.opacity = this.options.opacity;
    this.tiltWrapper.appendChild(el);
    this.imgElems.push(el);
  }

  if (!this.options.bgfixed) {
    this.imgElems.push(this.tiltImgBack);
    ++this.options.extraImgs;
  }

  // add it to the DOM and remove original img element.
  this.el.parentNode.insertBefore(this.tiltWrapper, this.el);
  this.el.parentNode.removeChild(this.el);

  // tiltWrapper properties: width/height/left/top
  this.view = {
    width: this.tiltWrapper.offsetWidth,
    height: this.tiltWrapper.offsetHeight
  };
};

另一個原型方式是用於監聽鼠標事件之類的:插件

TiltFx.prototype._initEvents = function() {
  var self = this,
    moveOpts = self.options.movement;

  // mousemove event..
  this.tiltWrapper.addEventListener('mousemove', function(ev) {
    requestAnimationFrame(function() {
      // mouse position relative to the document.
      var mousepos = getMousePos(ev),
        // document scrolls.
        docScrolls = {
          left: document.body.scrollLeft + document.documentElement.scrollLeft,
          top: document.body.scrollTop + document.documentElement.scrollTop
        },
        bounds = self.tiltWrapper.getBoundingClientRect(),
        // mouse position relative to the main element (tiltWrapper).
        relmousepos = {
          x: mousepos.x - bounds.left - docScrolls.left,
          y: mousepos.y - bounds.top - docScrolls.top
        };

      // configure the movement for each image element.
      for (var i = 0, len = self.imgElems.length; i < len; ++i) {
        var el = self.imgElems[i],
          rotX = moveOpts.rotateX ? 2 * ((i + 1) * moveOpts.rotateX / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.rotateX / self.options.extraImgs) : 0,
          rotY = moveOpts.rotateY ? 2 * ((i + 1) * moveOpts.rotateY / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateY / self.options.extraImgs) : 0,
          rotZ = moveOpts.rotateZ ? 2 * ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) : 0,
          transX = moveOpts.translateX ? 2 * ((i + 1) * moveOpts.translateX / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.translateX / self.options.extraImgs) : 0,
          transY = moveOpts.translateY ? 2 * ((i + 1) * moveOpts.translateY / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateY / self.options.extraImgs) : 0,
          transZ = moveOpts.translateZ ? 2 * ((i + 1) * moveOpts.translateZ / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateZ / self.options.extraImgs) : 0;

        el.style.WebkitTransform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';
        el.style.transform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';
      }
    });
  });

  // reset all when mouse leaves the main wrapper.
  this.tiltWrapper.addEventListener('mouseleave', function(ev) {
    setTimeout(function() {
      for (var i = 0, len = self.imgElems.length; i < len; ++i) {
        var el = self.imgElems[i];
        el.style.WebkitTransform = 'perspective(' + moveOpts.perspective + 'px) translate3d(0,0,0) rotate3d(1,1,1,0deg)';
        el.style.transform = 'perspective(' + moveOpts.perspective + 'px) translate3d(0,0,0) rotate3d(1,1,1,0deg)';
      }
    }, 60);

  });

  // window resize
  window.addEventListener('resize', throttle(function(ev) {
    // recalculate tiltWrapper properties: width/height/left/top
    self.view = {
      width: self.tiltWrapper.offsetWidth,
      height: self.tiltWrapper.offsetHeight
    };
  }, 50));
};

咱們能夠看到,監聽mousemove的事件處理函數中的計算比較複雜,關鍵的部分就是在這裏:

var el = self.imgElems[i],
          rotX = moveOpts.rotateX ? 2 * ((i + 1) * moveOpts.rotateX / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.rotateX / self.options.extraImgs) : 0,
          rotY = moveOpts.rotateY ? 2 * ((i + 1) * moveOpts.rotateY / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateY / self.options.extraImgs) : 0,
          rotZ = moveOpts.rotateZ ? 2 * ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.rotateZ / self.options.extraImgs) : 0,
          transX = moveOpts.translateX ? 2 * ((i + 1) * moveOpts.translateX / self.options.extraImgs) / self.view.width * relmousepos.x - ((i + 1) * moveOpts.translateX / self.options.extraImgs) : 0,
          transY = moveOpts.translateY ? 2 * ((i + 1) * moveOpts.translateY / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateY / self.options.extraImgs) : 0,
          transZ = moveOpts.translateZ ? 2 * ((i + 1) * moveOpts.translateZ / self.options.extraImgs) / self.view.height * relmousepos.y - ((i + 1) * moveOpts.translateZ / self.options.extraImgs) : 0;

        el.style.WebkitTransform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';
        el.style.transform = 'perspective(' + moveOpts.perspective + 'px) translate3d(' + transX + 'px,' + transY + 'px,' + transZ + 'px) rotate3d(1,0,0,' + rotX + 'deg) rotate3d(0,1,0,' + rotY + 'deg) rotate3d(0,0,1,' + rotZ + 'deg)';

這裏咱們根據鼠標的位置,計算出了各個圖層對應的偏移量和旋轉角度,而後對它們進行變換便可。
最後mouseleave以後,咱們再把個個圖層恢復到初始位置就好了。

Demo:http://codepen.io/CodingMonkeyzh/pen/jPYNyr

相關文章
相關標籤/搜索