Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme.

I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need to copy the .js content into script.js. However, after doing these steps, nothing seems to change on my localhost website. Any guidance or assistance would be highly appreciated! 🧡

Below is the code snippet (includes HTML, CSS, and JS):

<canvas id="canvas"></canvas>

body,
html {
  margin: 0px;
  padding: 0px;
  position: fixed;
  background: rgb(30, 30, 30);
  cursor: none;
}
... (the rest of the code follows here)

Answer â„–1

Here's an example implementation:

window.init = function(elemid) {
  let canvas = document.getElementById(elemid),
    ctx = canvas.getContext("2d"),
    w = (canvas.width = window.innerWidth),
    h = (canvas.height = window.innerHeight);
  ctx.fillStyle = "rgba(30,30,30,1)";
  ctx.fillRect(0, 0, w, h);
  return {ctx:ctx,canvas:canvas};
}

window.requestAnimFrame = function() {
  return (
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback);
    }
  );
};

window.spaceworm = function () {
  //functions definition

  //class definition
  class segment {
    constructor(x, y, length) {
      this.boundary = Math.random()*1.9+0.1;
      this.x0 = x;
      this.y0 = y;
      this.angle = Math.random() * 2 * Math.PI;
      this.x1 = this.x0 + length * Math.cos(this.angle);
      this.y1 = this.y0 + length * Math.sin(this.angle);
      this.length = length;
    }
    update(x, y) {
      this.x0 = x;
      this.y0 = y;
      this.angle = Math.atan2(this.y1 - this.y0, this.x1 - this.x0);
      this.x1 = this.x0 + this.length * Math.cos(this.angle);
      this.y1 = this.y0 + this.length * Math.sin(this.angle);
    }
  }
  class rope {
    constructor(tx, ty, length, boundary, segmentsToLengthRatio, type) {
      if(type == "l"){
        this.resolution = length / 2;
      }else{
        this.resolution = length / segmentsToLengthRatio;
      }
      this.type = type;
      this.length = length;
      this.segments = [];
      this.segments.push(new segment(tx, ty, this.length / this.resolution));
      for (let i = 1; i < this.resolution; i++) {
        this.segments.push(
          new segment(this.segments[i - 1].x1, this.segments[i - 1].y1, this.length / this.resolution)
        );
      }
      this.boundary = boundary;
    }
    update(target) {
      this.segments[0].update(target.x, target.y);
      for (let i = 1; i < this.resolution; i++) {
        this.segments[i].update(this.segments[i - 1].x1, this.segments[i - 1].y1);
      }
    }
    show() {
      if(this.type == "l"){
      ctx.beginPath();
      for (let i = 0; i < this.segments.length; i++) {
        ctx.lineTo(this.segments[i].x0, this.segments[i].y0);
      }
      ctx.lineTo(
        this.segments[this.segments.length - 1].x1,
        this.segments[this.segments.length - 1].y1
      );
      ctx.strokeStyle = "white";
      ctx.lineWidth = this.boundary;
      ctx.stroke();

      ctx.beginPath();
      ctx.arc(this.segments[0].x0, this.segments[0].y0, 1, 0, 2 * Math.PI);
      ctx.fillStyle = "white";
      ctx.fill();

      ctx.beginPath();
      ctx.arc(
        this.segments[this.segments.length - 1].x1,
        this.segments[this.segments.length - 1].y1,
        2,
        0,
        2 * Math.PI
      );
      ctx.fillStyle = "white";
      ctx.fill();
      }else{
      for (let i = 0; i < this.segments.length; i++) {
        ctx.beginPath();
        ctx.arc(this.segments[i].x0, this.segments[i].y0, this.segments[i].boundary, 0, 2*Math.PI);
        ctx.fillStyle = "white";
      ctx.fill();
      }
        ctx.beginPath();
      ctx.arc(
        this.segments[this.segments.length - 1].x1,
        this.segments[this.segments.length - 1].y1,
        2, 0, 2*Math.PI
      );
      ctx.fillStyle = "white";
      ctx.fill();
      }
    }
  }

  //setting up canvas
  let ctx = init("canvas").ctx,
    canvas = init("canvas").canvas,
    w = (canvas.width = window.innerWidth),
    h = (canvas.height = window.innerHeight),
    ropes = [];

  //variables definition
  let nameOfVariable = "value",
    mouse = {},
    last_mouse = {},
    rl = 50,
    randl = [],
    target = { x: w/2, y: h/2 },
    last_target = {},
    t = 0,
    q = 10,
    da = [],
    type = "l";

  for (let i = 0; i < 100; i++) {
    if(Math.random() > 0.25){
        type = "l";
      }else{
        type = "o";
      }
    ropes.push(
      new rope(
        w / 2,
        h / 2,
        (Math.random() * 1 + 0.5) * 500,
        Math.random() * 0.4 + 0.1,
        Math.random()*15+5,
        type
      )
    );
    randl.push(Math.random() * 2 - 1);
    da.push(0);
  }

  //place for objects in animation
  function draw() {
    
    if (mouse.x) {
      target.errx = mouse.x - target.x;
      target.erry = mouse.y - target.y;
    } else {
      target.errx =
        w / 2 +
        (h / 2 - q) *
          Math.sqrt(2) *
          Math.cos(t) /
          (Math.pow(Math.sin(t), 2) + 1) -
        target.x;
      target.erry =
        h / 2 +
        (h / 2 - q) *
          Math.sqrt(2) *
          Math.cos(t) *
          Math.sin(t) /
          (Math.pow(Math.sin(t), 2) + 1) -
        target.y;
    }

    target.x += target.errx / 10;
    target.y += target.erry / 10;

    t += 0.01;
    
    for (let i = 0; i < ropes.length; i++) {
      if (randl[i] > 0) {
        da[i] += (1 - randl[i]) / 10;
      } else {
        da[i] += (-1 - randl[i]) / 10;
      }
      ropes[i].update({
        x:
          target.x +
          randl[i] * rl * Math.cos((i * 2 * Math.PI) / ropes.length + da[i]),
        y:
          target.y +
          randl[i] * rl * Math.sin((i * 2 * Math.PI) / ropes.length + da[i])
      });
      ropes[i].show();
    }
    last_target.x = target.x;
    last_target.y = target.y;
  }

  //mouse position
  canvas.addEventListener(
    "mousemove",
    function (e) {
      last_mouse.x = mouse.x;
      last_mouse.y = mouse.y;

      mouse.x = e.pageX - this.offsetLeft;
      mouse.y = e.pageY - this.offsetTop;
    },
    false
  );
  
  canvas.addEventListener("mouseleave", function(e) {
    mouse.x = false;
    mouse.y = false;
  });

  //animation frame
  function loop() {
    window.requestAnimFrame(loop);
    ctx.clearRect(0, 0, w, h);
    draw();
  }

  //window resize
  window.addEventListener("resize", function () {
    (w = canvas.width = window.innerWidth),
      (h = canvas.height = window.innerHeight);
    loop();
  });

  //animation runner
  loop();
  setInterval(loop, 1000 / 60);
};

window.onload = spaceworm;
body,
html {
  margin: 0px;
  padding: 0px;
  position: fixed;
  background: rgb(30, 30, 30);
  cursor: none;
}
<canvas id="canvas"></canvas>





Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

Highchart encountering issues with multiple Y axes

My highchart is causing Chrome to crash when I add the second series. I am unable to see the Chrome console for debugging purposes.. :( Does anyone have any suggestions? $(function () { var chart; $(document).ready(function() { chart ...

What are some effective methods for testing web applications on mobile devices?

While I may not have the funds to purchase mobile phones and iPhones, I am eager to ensure my web applications can be accessed on mobile devices. Are there any software solutions available to simulate these devices, or what steps should I take? ...

verify access with mysql database

Need urgent assistance, sorry if this is a repeated query due to my username! I am facing an issue with my login page. I want it to redirect to my home page when authentication fails by cross-checking input with a MySQL database which should output succes ...

Align an image in the middle with a heading

I am currently working on aligning a picture and heading in a header section. My goal is to center both elements, with the picture being twice as tall as the heading. So far, I have them stacked one above the other: .body { font: 15px/1.5 Arial, Helveti ...

"Utilizing a Handlebars Helper to Evaluate if Two Values (v1 and v2) are Equal, and Displaying Content from

To make the actual call, I require something along these lines: <script id="messagesTemplate" type="text/x-handlebars-template"> {{#each messages.messages}} {{#each to}} {{#ifCond username messages.sessionUserName}} <h1> ...

Achieving a seamless blend of parent background with child background: A step-by

I am trying to make the parent background color overlap the child background color in two divs. Currently, the child's background is overlapping the parent's background. Please refer to the JS-Fiddle link below for more information: <div id=" ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

403 Malicious Path Middleware Error in Express.js

Encountering an error when sending a post request to my server, but only on the production server - whereas the staging server is functioning properly. Both servers are hosted on AWS Ubuntu instances. Investigating the stack trace, it appears that the err ...

What is the proper way to credit the glyphicons element in Twitter's bootstrap framework?

According to the section on icons in the Base CSS page of GitHub's Twitter bootstrap, Glyphicons Halflings were not originally available for free. However, thanks to an agreement between Bootstrap and the creators of Glyphicons, developers can now use ...

Break apart animation similar to the 🎊 emoji using CSS styling

I am attempting to create an animation of a circle splitting open on two sides, similar to the ...

Encountering the error message "Attempting to access properties of undefined (specifically 'map')". Despite having the array properly declared and imported

I am facing an issue while trying to iterate through an array and display names for each person. Despite declaring the array properly, it is returning as undefined which is causing the .map function to fail. Can you help me figure out where I am making a m ...

Bootstrap form validation issues

Currently, I am utilizing Vue.js along with Bootstrap for the creation of a website. In this process, I have set up a form on which I am implementing my custom validation logic. Everything seems to be functioning correctly until the moment when the user hi ...

What is the best way to integrate custom JavaScript files into a Vue project?

I recently downloaded an HTML template from a website and now I am looking to convert the entire template into a Vue CLI project. The template includes jQuery and other custom JavaScript files. While I was able to use npm packages for jQuery and Bootstrap, ...

Clicking on a card will cause it to expand

Exploring Material-UI-React for the first time to create expanding cards, I've encountered an issue where all cards expand when one is clicked. How can I modify my code so that only the clicked card expands without affecting the others? const useSt ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

The border on the right side of the accordion does not continue down

After creating an HTML page with an accordion in one div and a menu in another, I added a simple border styling to the right side of the menu using CSS properties like height, border-right-width, border-right-style, and border-right-color. height:100%; b ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...