update() { this.x += this.directionX; if(this.x > canvas.width + this.radius) { this.x = -this.radius; } this.render(); } 基本的なパーティクルでは、上記のように「丸の位置を少しずつ動かす」という処理をしています。 今回は、ここのupdateの処理の中で計算をします。 マウスの位置取得 まず、マウスの位置を取得する必要があります。そのためにmousemoveイベントを登録し、マウスカーソルの位置を変数に入れておくようにします。 const mouse = { x: null, y: null } window.addEventListener('mousemove', (event) => { mouse.x = event.x; mouse.y = event.y; }
![【canvas初学者必見】マウスカーソルを避けていくパーティクルアニメーションを作ろう! | 株式会社LIG(リグ)|DX支援・システム開発・Web制作](https://cdn-ak-scissors.b.st-hatena.com/image/square/d93c3db1fce4fefd088408556e4cd7fdbed8b8e9/height=288;version=1;width=512/https%3A%2F%2Fliginc.co.jp%2Fwp-content%2Fuploads%2F2021%2F08%2Fec_210827_e2_OGP.png)