DEV Community

Anoop Patel
Anoop Patel

Posted on

Cursor Follower using JS

Cursor follower using html, css and js

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3D Cursor Follower</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      background: #000;
    }
    canvas {
      display: block;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // Set canvas to full screen
    function resizeCanvas() {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    }
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    // Circle object
    const circle = {
      x: canvas.width / 2,
      y: canvas.height / 2,
      size: 30,
      z: 0, // Simulated depth
      maxZ: 300, // Maximum depth
      color: '#ff0000'
    };

    // Mouse coordinates
    const mouse = {
      x: canvas.width / 2,
      y: canvas.height / 2
    };

    // Update mouse position
    window.addEventListener('mousemove', (event) => {
      mouse.x = event.clientX;
      mouse.y = event.clientY;

      // Simulate depth by mapping x and y distance to z
      const distX = Math.abs(canvas.width / 2 - mouse.x);
      const distY = Math.abs(canvas.height / 2 - mouse.y);
      circle.z = Math.min(circle.maxZ, distX + distY);
    });

    function drawCircle() {
      const scale = 1 - circle.z / circle.maxZ; // Scale based on depth
      ctx.beginPath();
      ctx.arc(circle.x, circle.y, circle.size * scale, 0, Math.PI * 2);
      ctx.fillStyle = circle.color;
      ctx.fill();
      ctx.closePath();
    }

    function animate() {
      // Clear canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // Move circle toward the mouse smoothly
      circle.x += (mouse.x - circle.x) * 0.1;
      circle.y += (mouse.y - circle.y) * 0.1;

      // Draw circle
      drawCircle();

      requestAnimationFrame(animate);
    }

    animate();
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)