9
10

More than 5 years have passed since last update.

マウスの動きで背景パララックス

Last updated at Posted at 2016-10-11

デモ:http://codepen.io/mo4_9/pen/PGRjoX

動かしたい分だけ大きめの画像を設定

20px大きめの画像
#bg{
  width: calc(100% + 20px);
  height: calc(100% + 20px);
}

レイヤーを複数重ねて視差効果を生む

const ww = window.innerWidth;
const wh = window.innerHeight;
const hw = ww / 2;
const hh = wh / 2;
const pm = 20; // parallax margin

const $bg = $('#bg');
const $box = $('#box');

$(window).on('mousemove', (e) => {

  // 中心から端までの距離を、余分に大きくとった背景画像の分(ここでは20÷2=10px)に割り当てる
  const mw = ( e.clientX - hw ) / hw * ( pm / 2 ); // 0.0 ~ 10.0
  const mh = ( e.clientY - hh ) / hh * ( pm / 2 );
  console.log( mw, mh );

  $bg.css('margin-left', mw );
  $bg.css('margin-top', mh );

  // これでも同じ
  // $bg.css('left', hw + mw );
  // $bg.css('top', hh + mh );

  $box.css('margin-left', mw * -0.5 ); // 逆方向
  $box.css('margin-top', mh * 0.5);

})

ライブラリも発見
Interactive BG (Background) by Pete R.

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10