...

Web Development

Create a Neon Cursor Effect with Three.js: HTML, CSS, and JavaScript Tutorial

Web Development

Create a Neon Cursor Effect with Three.js: HTML, CSS, and JavaScript Tutorial

Table of Contents

Introduction

In this tutorial, we will learn how to create an impressive neon cursor effect using Three.js, HTML, CSS, and JavaScript. This effect adds a modern and interactive touch to your website. We will break down each part of the code so you can easily understand and customize this effect for your own projects.

Why Use a Neon Cursor Effect?

The neon cursor effect is an elegant visual addition that can enhance the user experience on your website. It follows the movement of the mouse, creating a dynamic glowing trail that captures attention. This type of effect is particularly suitable for portfolio websites, landing pages, or any site aiming to provide a unique and engaging user interaction. By using modern visual effects like a neon cursor, you can differentiate your website and make navigation more immersive.

Required Tools and Technologies

To create this neon cursor effect, we will need several technologies and tools:

  • Three.js: a powerful JavaScript library for creating 3D graphics in the browser.
  • HTML and CSS: to structure and style our web page.
  • JavaScript: to animate and manage the user interaction with the cursor effect.
  • Code Editor (such as VS Code): to write and modify the code.
  • Compatible Browsers: Modern browsers such as Chrome, Firefox, or Edge that support WebGL, which is required for running Three.js.

This combination of tools will allow you to implement a high-performance and visually appealing neon cursor.

HTML Page Structure

To begin, we will establish the basic HTML structure that will serve as the foundation for our neon cursor effect. Here is the basic HTML code:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Neon Cursor</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</head>
<body>
    <div id="app">
        <section class="hero">
            <div class="wrap-content">
              <h1 class="main-title">Digital marketing agency <br> <strong>MonDesign Web</strong></h1>
            </div>
          </section>
    </div>
    <script src="index.js" type="module"></script>
</body>
</html>
  

Explanation of the HTML Structure

  • DOCTYPE and HTML Structure: This document begins with the declaration to define the HTML version. Then, the document language is set to English using lang="en".
  • Head Section :
    • The meta charset="UTF-8" ensures that the document uses UTF-8 character encoding.
    • meta http-equiv="X-UA-Compatible" ensures compatibility with Internet Explorer.
    • meta name="viewport" rend la page responsive.
    • Le lien vers la feuille de style styles.css définit les styles de la page.
    • Le script de Three.js est inclus via un CDN pour faciliter la création des effets graphiques.
  • Body Section :
    • the div avec l’id app est le conteneur principal pour notre contenu.
    • La section hero est l’endroit où nous plaçons le texte principal avec une mise en page centrée.
    • Le script index.js est chargé à la fin pour assurer que le DOM est entièrement chargé avant que le JavaScript ne soit exécuté.

Setting Up CSS Styles

Next, we define the base styles for our effect in the styles.css file. Here is an example of CSS code:

  :root {
    --surface-900: #131320;
    --primary-100: #B89CFC;
}

body, html, #app {
    margin: 0;
    width: 100%;
    height: 100%;
}

#app {
    overflow: hidden;
    touch-action: pan-up;
    color: #ffffff;
    font-family: "Montserrat", sans-serif;
    text-align: center;
}

#app canvas {
    display: block;
    position: fixed;
    z-index: -1;
    top: 0;
    left: 0;
}

.hero {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #FFFFFF;
}

.main-title {
    font-size: 24px;
    font-weight: 400;
    color: #FFFFFF;
}

.main-title strong {
    color: var(--primary-100);
}

@media screen and (min-width: 640px) {
    .main-title {
        font-size: 34px;
    }
}

@media screen and (min-width: 1024px) {
    .main-title {
        font-size: 42px;
    }
}

@media screen and (min-width: 1536px) {
    .main-title {
        font-size: 60px;
    }
}
  

CSS Analysis:

  • Base Styles: Default margins are removed, and the height and width are set to 100% for body, html, and #app so the cursor effect can cover the entire screen.
  • #app Styles: overflow: hidden prevents unwanted scrolling, while touch-action: pan-up optimizes behavior on touch screens. The text is centered using text-align: center, and a dark background is used to highlight the neon effect.
  • Canvas Positioning: The canvas used to draw the neon effect is positioned in the background with z-index: -1, allowing it to remain behind other elements.
  • CSS Variables: CSS variables are used to easily manage colors and page themes.
  • Responsive Design: Font sizes for .main-title adjust according to screen width to ensure good readability on all devices.

Introduction to Three.js

Three.js is a JavaScript library that simplifies the creation of complex 3D graphics in the browser. It is essential for producing sophisticated visual effects, such as the neon cursor, by leveraging WebGL, an API used for 3D rendering.

Why Choose Three.js?

Three.js is widely adopted for its ease of use compared to other more complex 3D libraries. It offers great flexibility and a wide range of features for creating animations and interactive graphics. For our neon cursor, Three.js allows us to easily manipulate shaders and 3D objects needed to produce realistic glowing effects.

Implementing JavaScript for the Neon Effect

Le JavaScript est la clé pour animer et gérer le comportement du curseur néon. Nous allons utiliser Three.js pour initier et contrôler cet effet.

Basic JavaScript Code

The following script should be placed in the index.js file:

  import { neonCursor } from 'https://unpkg.com/threejs-toys@0.0.8/build/threejs-toys.module.cdn.min.js';

const root = document.getElementById("app");

const options = {
    el: root,
    shaderPoints: 20,
    curvePoints: 88,
    curveLerp: 0.8,
    radius1: 5,
    radius2: 25,
    velocityTreshold: 10,
    sleepRadiusY: 200,
    sleepRadiusX: 200,
    sleepTimeCoefX: 0.0025,
    sleepTimeCoefY: 0.0025
};

neonCursor(options);
  

Explanation of the JavaScript Code

  • Importing Three.js: We import the neonCursor function from the threejs-toys library, a module that simplifies the use of Three.js for this specific effect.
  • Cursor Options: The code uses several parameters to define the behavior and appearance of the neon cursor, such as shaderPoints (number of glowing points), curvePoints (number of curve points), and radius1 and radius2 (the radii of the cursor trail). These options allow you to customize the effect very precisely.
  • Initialization: By calling neonCursor(options), we apply the neon effect to the specified HTML element, here the container with the id app.
  const options = {
    el: root,
    shaderPoints: 20,
    curvePoints: 88,
    curveLerp: 0.8,
    radius1: 5,
    radius2: 25,
    velocityTreshold: 10,
    sleepRadiusY: 200,
    sleepRadiusX: 200,
    sleepTimeCoefX: 0.0025,
    sleepTimeCoefY: 0.0025
};
  
  • el: root: Specifies the HTML element where the neon effect will be applied (the element with the id “app”).

  • shaderPoints: 20: Defines the number of glowing points of the cursor.

  • curvePoints: 88 : Définit le nombre de points qui forment la courbe suivie par le curseur.

  • curveLerp: 0.8: Controls the smoothness of the curve transitions for a smoother movement.

  • radius1: 5: Determines the radius of the small sphere that represents the start of the cursor.

  • radius2: 25: Determines the radius of the large sphere that forms the cursor trail.

  • velocityTreshold: 10: Sets the minimum speed at which the cursor begins to move.

  • sleepRadiusY: 200 and sleepRadiusX: 200: Specify the cursor sensitivity when the mouse is idle.

  • sleepTimeCoefX: 0.0025 and sleepTimeCoefY: 0.0025: Control the cursor’s reaction time when the mouse stops moving.

  • neonCursor(options): Applies the neon effect using the options defined above.

Troubleshooting and Optimization

Even with well-structured code, adjustments may be necessary to optimize performance or resolve specific issues. Here are a few tips:

  • Error Checking: Use the browser console to identify JavaScript errors that might prevent the cursor from functioning correctly.
  • Performance Optimization: Reduce the number of glowing points or adjust parameters to lighten the load on the GPU, especially on mobile devices.
  • Browser Compatibility: Make sure your effect works well on all modern browsers. Test regularly on different platforms to avoid incompatibilities.

Tests et Validation

It is crucial to test your neon cursor effect on various browsers and devices to ensure a consistent and high-performance user experience.

  • Performance Testing: Use tools like Google Lighthouse to analyze performance and the impact on your page’s loading time.
  • Compatibility Testing: Check the display and behavior of the effect on browsers such as Chrome, Firefox, Edge, and Safari.

Advanced Improvements

Once you have mastered the basic effect, you can go further by adding advanced features to enhance your website’s interactivity:

  • Custom Interactions: For example, change the trail color based on user clicks or in response to specific events.
  • Integration with Other Libraries: Combine Three.js with other JavaScript libraries to add additional animations or more complex interactions.

Conclusion

This tutorial has guided you step by step to create an impressive neon cursor effect using Three.js, HTML, CSS, and JavaScript. This effect adds a modern and dynamic touch to your website, making navigation more engaging. Feel free to customize the parameters and experiment with different configurations to adapt this effect to your specific needs.

Share it

error:
en_US
#!trpst#trp-gettext data-trpgettextoriginal=1946#!trpen#Seraphinite Accelerator#!trpst#/trp-gettext#!trpen##!trpst#trp-gettext data-trpgettextoriginal=1947#!trpen#Optimized by #!trpst#trp-gettext data-trpgettextoriginal=1946#!trpen#Seraphinite Accelerator#!trpst#/trp-gettext#!trpen##!trpst#/trp-gettext#!trpen#
#!trpst#trp-gettext data-trpgettextoriginal=1948#!trpen#Turns on site high speed to be attractive for people and search engines.#!trpst#/trp-gettext#!trpen#