10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

常にマウスの方を向くボックス

Last updated at Posted at 2017-02-20

概要

  • マウスの動きに合わせて傾き、角度を変えるボックス
  • 左から右や、上から下など反対側にマウスを動かしたときのボックスの表示が同じにみえるため、CSSのPerspectiveプロパティで遠近感を出す。

デモ

http://codepen.io/viscosenpai/pen/NdZyqW

コード

index.html
<main>
  <div id="box">Hello World!</div>
</main>
style.css
body {
  position: relative;
  margin: 0;
  width: 100%;
  height: 100vh;
}

p {
  margin: 0;
}

main {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  perspective: 800px;
}

#box {
  display: block;
  background: #ff9191;
  width: 400px;
  height: 200px;
}
script.js
var body = document.body;
var box = document.getElementById('box');
var mouseHandler = function (e) {
  var docW = body.clientWidth / 2;
  var docH = body.clientHeight / 2;
  var moveX = (e.clientX - docW) / 10;
  var moveY = (e.clientY - docH) / 10;
  box.style.webkitTransform = 'translate(' + -moveX + 'px, ' + -moveY + 'px)';
  box.style.webkitTransform += 'rotateX(' + -moveY + 'deg)';
  box.style.webkitTransform += 'rotateY(' + moveX + 'deg)';
}
body.addEventListener('mousemove', mouseHandler, false);

ポイント

perspectiveの値を小さくすればより奥行きがダイナミック(?)になります。
ボックスの傾き、回転の取得値を反転(+ から - へ)したい場合、変数の先頭にマイナスをつければそのまま反転します。今回一番の収穫かも(517 => -517)

最後に

もっとこうした方がパフォーマンス的にええで。というようなことがあれば指摘をお願いします。

10
11
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
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?