Creating Face That Follows Mouse Cursor Like MetaMask Fox

This time, I created a js code that a 3D face follows a mouse cursor like MetaMask fox. In this post, I will show you how to use it.

Tibetan Sand Fox That Follows Mouse Cursor

Demo

Files Used

The following four files were used this time.

three.min.js: JavaScript library and API used to create and display 3D computer graphics in a web browser
GLTFLoader.js: To load GLTF and GLB 3D data
mouse-follower.min.js: To follow mouse cursor
3D data (gltf or glb): GLTF or GLB 3D data to display

Download

Download three.min.js and GLTFLoader.js from the menu on the left of the following site. Those files are together in one compressed file and the file paths are below.

three.min.js: /three.js-master/build/three.min.js
GLTFLoader.js: /three.js-master/examples/js/loaders

Code

First, write the code below in the part where you want to display 3D.

<div id="main_canvas">
    <canvas id="canvas" width="500px" height="500px"></canvas>
</div>

Then add the JS code to follow the mouse. Align the canvas size to the same as the canvas size above. There are two type camera settings and several type light settings. Refer to the URL below for the setting methods. Then write the path of the 3D data to gltf_glb_path

Camera – three.js docs

Light – three.js docs

// canvas size: [width, height]
const canvas_size = [500, 500];
// camera: new THREE.PerspectiveCamera(viewing angle, aspect ratio, shooting start, shooting end)
const camera = new THREE.PerspectiveCamera(45, canvas_size[0] / canvas_size[1], 1, 10000);
// lights: [new THREE.AmbientLight(color, intensity)] multiple lights can be added here
const lights = [new THREE.AmbientLight(0xffffff, 3.8)];
// GLTF or GLB file path
const gltf_glb_path = 'tibetan-sand-fox.glb';

window.addEventListener('DOMContentLoaded', mouse_follower(canvas_size, camera, lights, gltf_glb_path));

Finally, rewrite the following URLs and specify the URLs of the JS files you saved.

<script src="http://example/javascript/three.min.js"></script>
<script src="http://example/javascript/GLTFLoader.js"></script>
<script src="http://example/javascript/mouse-follower.min.js"></script>
<script src="http://example/javascript/mouse-follower-setting.js"></script>

To Conclude

That concludes how to make face that follows mouse cursor. Adding movement to 3d will make it look better so I think this code is good for 3d designer's portfolio sites.