...

Web Development

Create an Interactive Spider Web Cursor Effect with HTML, CSS, and JavaScript

Web Development

Create an Interactive Spider Web Cursor Effect with HTML, CSS, and JavaScript

Table of Contents

In this article, we will explore how to create an impressive Spider Web cursor effect using HTML, CSS, and JavaScript. This effect adds an engaging interactive dimension to your website, captivating users with a network of points and lines that dynamically connect to the cursor, along with a spider icon that follows its movement.

We will break down each part of the code, explain how it works, and guide you through the complete implementation so that you can customize this effect for your own projects.

Introduction

The Spider Web Cursor effect is a unique visual animation where points appear on the screen and dynamically connect with lines based on the mouse cursor's position. This type of effect is ideal for creative websites, interactive portfolios, or homepages that aim to capture users' attention and enhance their browsing experience.

We will use a simple HTML document to structure the page, CSS for styling and layout, and JavaScript to handle the animation and real-time interaction.

HTML Page Structure

To get started, we will create the basic structure of our web page using HTML. Here is the HTML code you can use:

  <!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spider Cursor Effect</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h3 id="centerText">@mondesignweb</h3>
    <canvas id="spiderCanvas"></canvas>
    <script src="script.js"></script>
</body>
</html>
  

Explanation of the HTML Structure

  • DOCTYPE and HTML Structure: Define the HTML version used and the language of the document as French.

  • Meta Tags  :
    • 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.
    • The link to the stylesheet style.css sets the styles for the page.
  • Body Section :
    • h3: @mondesignweb : Displays centered text on the page.
    • <canvas id="spiderCanvas"></canvas> : The element <canvas> where the spider web drawing will take place.
    • : Links the JavaScript file to animate the effect.

Setting Up CSS Style

The CSS defines the visual appearance of our page and manages the positioning of elements, including the canvas (canvas) for the spider web animation and the centered text.

  body {
    margin: 0;
    overflow: hidden;
    background: #410000;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    position: relative;
    cursor: pointer;
}

canvas {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
}

h3#centerText {
    color: white;
    font-size: 24px;
    z-index: 10;
    position: absolute;
    text-align: center;
}


  

CSS Analysis:

body :

  • margin: 0; : Removes the default margins.
  • overflow: hidden;: Hides any content that overflows outside the page.
  • background: #410000;: Applies a dark red background color to create a dramatic effect.
  • display: flex; align-items: center; justify-content: center; : Centers all child elements horizontally and vertically.
  • height: 100vh;: Ensures that the body of the page occupies the entire height of the viewport.
  • cursor: pointer; : Changes the default cursor to a pointer icon when hovering over the page.

canvas :

  • display: block; : Displays the canvas as a block-level element.
  • position: absolute; : Positions the canvas relative to the window.
  • top: 0; left: 0;: Places the canvas at the top-left of the window, covering the entire page.

h3#centerText :

  • color: white;: Sets the text color to white.
  • font-size: 24px;: Sets the text font size.
  • z-index: 10;: Ensures the text appears above the canvas.
  • position: absolute;: Positions the text absolutely in the center of the page.

Implementation of Animation in JavaScript

JavaScript is used to animate the “Spider Web” cursor effect. Here is the JavaScript code that should be placed in the script.js file:

  const canvas = document.getElementById('spiderCanvas');
const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

let points = [];

const POINTS_COUNT = 300;
const LINE_LENGTH = 200;
const CURSOR_RADIUS = 50;

const spiderIcon = new Image();
spiderIcon.src = 'spider.png'; // Remplacez par le chemin de votre icône de spider

const SPIDER_ICON_SIZE = 80;

for (let i = 0; i < POINTS_COUNT; i++) {
    points.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        velocityX: (Math.random() - 0.5) * 2,
        velocityY: (Math.random() - 0.5) * 2
    });
}

let cursor = { x: canvas.width / 2, y: canvas.height / 2 };

document.addEventListener('mousemove', function(event) {
    cursor.x = event.clientX;
    cursor.y = event.clientY;
});

function drawSpiderWeb() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    points.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 2, 0, Math.PI * 2);
        ctx.fillStyle = 'white';
        ctx.fill();
    });

    points.forEach(point => {
        const distance = Math.hypot(cursor.x - point.x, cursor.y - point.y);
        if (distance < LINE_LENGTH) {
            ctx.beginPath();
            ctx.moveTo(cursor.x, cursor.y);
            ctx.lineTo(point.x, point.y);
            ctx.strokeStyle = `rgba(255, 255, 255, ${1 - distance / LINE_LENGTH})`;
            ctx.stroke();
        }
    });

    ctx.drawImage(
        spiderIcon,
        cursor.x - SPIDER_ICON_SIZE / 2,
        cursor.y - SPIDER_ICON_SIZE / 2,
        SPIDER_ICON_SIZE,
        SPIDER_ICON_SIZE
    );

    points.forEach(point => {
        point.x += point.velocityX;
        point.y += point.velocityY;

        if (point.x <= 0 || point.x >= canvas.width) point.velocityX *= -1;
        if (point.y <= 0 || point.y >= canvas.height) point.velocityY *= -1;
    });

    requestAnimationFrame(drawSpiderWeb);
}

window.addEventListener('resize', function() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});

drawSpiderWeb();
  

Explanation of the JavaScript Code

1. Initialization of the Canvas and 2D Context

  const canvas = document.getElementById('spiderCanvas');
const ctx = canvas.getContext('2d');
  
  • Select the <canvas> element with the ID spiderCanvas and store it in the variable canvas.
  • Utilisez getContext('2d') to obtain the 2D drawing context of the , stored in ctx, which allows you to draw shapes and images.

2. Set the Canvas Size

  canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

  
  • Sets the width and height of the so they match the size of the browser window. This ensures the covers the entire screen.

3. Creation of a Points Array

  let points = [];

  
  • Initializes an empty array points that will store the positions and velocities of the animated points.

4. Definition of Constants

  const POINTS_COUNT = 300;
const LINE_LENGTH = 200;
const CURSOR_RADIUS = 50;
  
  • POINTS_COUNT : Number of points that will be randomly generated on the .
  • LINE_LENGTH : Maximum distance at which a line will be drawn between the cursor and a point.
  • CURSOR_RADIUS : Radius of the circle around the cursor within which the lines are drawn.

5. Loading the Spider Icon

  const spiderIcon = new Image();
spiderIcon.src = 'spider.png'; // Remplacez par le chemin de votre icône de spider
const SPIDER_ICON_SIZE = 80;

  
  • Creates a new image spiderIcon and sets its source to load the spider icon.
  • SPIDER_ICON_SIZE : Defines the spider icon size as 80 pixels.

6. Generation of Random Points

  for (let i = 0; i < POINTS_COUNT; i++) {
    points.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        velocityX: (Math.random() - 0.5) * 2,
        velocityY: (Math.random() - 0.5) * 2
    });
}
  
  • A for loop generates POINTS_COUNT points, each with a random position (x, y) on the .
  • velocityX and velocityY are also randomly generated, determining the movement speed of the points along the X and Y axes.

7. Setting the Initial Cursor Position

  let cursor = { x: canvas.width / 2, y: canvas.height / 2 };

  
  • Initializes the cursor object with coordinates at the center of the .

8. Tracking Mouse Movement

  document.addEventListener('mousemove', function(event) {
    cursor.x = event.clientX;
    cursor.y = event.clientY;
});

  
  • Adds an event listener for mouse movement. On each move, the x and y coordinates of the cursor are updated according to the mouse position within the window.

9. drawSpiderWeb Function to Draw the Spider Web

  function drawSpiderWeb() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  • Clear the Canvas: Removes any previous drawings to avoid unwanted overlaps.
      points.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 2, 0, Math.PI * 2);
        ctx.fillStyle = 'white';
        ctx.fill();
    });
  
  • Draw the Points: Loops through each point in the points array and draws a small white circle at each point’s (x, y) position.
        points.forEach(point => {
        const distance = Math.hypot(cursor.x - point.x, cursor.y - point.y);
        if (distance < LINE_LENGTH) {
            ctx.beginPath();
            ctx.moveTo(cursor.x, cursor.y);
            ctx.lineTo(point.x, point.y);
            ctx.strokeStyle = `rgba(255, 255, 255, ${1 - distance / LINE_LENGTH})`;
            ctx.stroke();
        }
    });

  
  • Draw the Lines: For each point, calculates the distance between the point and the cursor. If the distance is less than LINE_LENGTH, a line is drawn between the cursor and the point, with opacity decreasing as the distance increases.
      ctx.drawImage(
        spiderIcon,
        cursor.x - SPIDER_ICON_SIZE / 2,
        cursor.y - SPIDER_ICON_SIZE / 2,
        SPIDER_ICON_SIZE,
        SPIDER_ICON_SIZE
    );
  
  • Draw the Spider Icon: Displays the spider icon at the center of the cursor’s position.
      points.forEach(point => {
        point.x += point.velocityX;
        point.y += point.velocityY;

        if (point.x <= 0 || point.x >= canvas.width) point.velocityX *= -1;
        if (point.y <= 0 || point.y >= canvas.height) point.velocityY *= -1;
    });
  
  • Update the Points’ Positions: Updates each point’s position based on its velocity. If a point reaches the edge of the , its direction is reversed (bounces off the edges).
      requestAnimationFrame(drawSpiderWeb);
}
  
  • Continuous Animation: requestAnimationFrame repeatedly calls the drawSpiderWeb function, creating a smooth animation loop.

10. Resizing the Canvas When the Window is Resized

  window.addEventListener('resize', function() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
});
  
  • Adjusts the size to match the new window size when it is resized.

11. Starting the Animation

  drawSpiderWeb();
  
  • Calls the drawSpiderWeb function to start the animation.

Conclusion

By following this tutorial, you have learned how to create an interactive Spider Web cursor effect using HTML, CSS, and JavaScript. This effect can make your website more dynamic and engaging while providing a unique user experience. Feel free to customize the settings to adjust the effect to your needs and style.

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#