トップへ(mam-mam.net/)

マウスカーソルにオブジェクトが追従するJavaScriptサンプ

マウスを動かしてください。
マウスカーソルにオブジェクトが追従してきます。
詳しくはソースをみてください。

<Img id="mov1" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov2" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov3" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov4" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov5" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov6" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov7" src="./imgs/piyokoko.gif" width="40" height="40">
<Img id="mov8" src="./imgs/piyokoko.gif" width="40" height="40">
<script>
class TMoveImgs{
  constructor(){
    this.pcnt=100;
    this.p=[];
    this.obj=[];
    for(let i=0;i<this.pcnt;i++){
      this.p[i]=[];
      this.p[i].x=100;
      this.p[i].y=200;
    }
    for(let i=0;i<8;i++){
      this.obj[i]=document.querySelector("#mov"+(i+1));
      this.obj[i].style.cssText="position:absolute;width:40px;height:40px;z-index:10000;";
    }
    window.onmousemove=this.mousemove.bind(this);
    setInterval(this.move.bind(this),20);
  }
  mousemove(){
    for(var i=0;i<(this.pcnt-1);i++){
      this.p[i].x=this.p[i+1].x;
      this.p[i].y=this.p[i+1].y;
    }
    this.p[this.pcnt-1].x=event.pageX;
    this.p[this.pcnt-1].y=event.pageY;
  }
  move(){
    for(let i=0;i<(this.pcnt-1);i++){
      this.p[i].x=this.p[i+1].x;
      this.p[i].y=this.p[i+1].y;
    }
    for(let i=0;i<8;i++){
      this.obj[i].style.left = (this.p[Math.floor(this.pcnt/8)*i].x+8)+"px";
      this.obj[i].style.top  = (this.p[Math.floor(this.pcnt/8)*i].y+8)+"px";
    }
  }
}
window.addEventListener('load', function(){
  MoveImgs=new TMoveImgs();
});
</script>