JavaScriptとCSSでマウスに追従するアニメーションを作成する方法

JavaScript

JavaScriptとCSSでマウスに追従するアニメーションを作成する方法を紹介します。

デモ

See the Pen マウス追従アニメーション by Sosak (@Sosak2021) on CodePen.

HTML

    <div id="cursor"></div>

CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body {
  min-height: 100vh;
  background: #000;
  overflow: hidden;
}
.container {
  position: relative;
  height: 100vh;
  overflow: hidden;
  z-index: 10; //#cursorより上にする

  // animation: animate 4s linear 10;
}

#cursor {
  position: absolute;
  top: 0;
  left: 0;
  border-radius: 50%;
  width: 250px;
  height: 250px;
  background: #0f0;
  transform: translate(-50%, -50%);
  z-index: 2000;
  animation: animate 4s linear infinite;
  z-index: 1; //containerより下にする
}

@keyframes animate {
  0% {
    filter: hue-rotate(0deg) blur(50px);
  }
  100% {
    filter: hue-rotate(360deg) blur(50px);
  }
}
#cursorのwidthとheightがマウスに追従したときの領域の大きさになります。 border-radiusなどで円にしたり、widthとheightをいじったり、clip-pathを使ったりとそれらの値をいじることでいろいろな形にできます。 transform: translate(-50%, -50%)は設定しないとマウスの中心にきません。 アニメーションは、filterのhue-rotateを使うことで、いろいろな値を設定することができます。 backgroundの色は、#0f0にすると、蛍光色に近い鮮やかなカラーになります。 filterのblurを設定すると、ぼやけさせることができます。

JavaScript


// カーソルに追従させる
const cursor = document.querySelector('#cursor');
window.onmousemove = e => {
  cursor.style.left = `${e.clientX}px`;
  cursor.style.top = `${e.clientY}px`;
}
onmousemoveを使うことで、マウスの動きに合わせていろいろできるようになります。 leftとtopの値をcursorに設定しているので、それをclientXとclientYに設定してあげれば、マウスの動きに合わせて追従できるようになります。

JavaScript

Posted by devsakaso