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

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

Discovering the method to extract text from an element within a search result with Selenium Webdriver

Struggling to extract a URL from Tripadvisor.com's search results using its element, my attempts have proven futile so far. Check out the code snippet below: from selenium.webdriver.common.keys import Keys from selenium import webdriver from seleniu ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

jQuery functions not functioning properly when triggered by an event

I encountered an issue with my page using jQuery and Bootstrap. Everything was functioning properly until I tried calling a function on an event, which resulted in the console showing an error message saying $(...).function is not a function. For example: ...

How to center elements using Bootstrap 4 and flexbox styling

Just starting out in web development. I currently have the following HTML: <section class="boxes"> <div class="container-fluid"> <div class="row"> <div class="col-12 col-lg-4 box1&q ...

The POST function in jQuery often returns the [Object object] result

Looking to extract a string from a PHP file using jQuery's post method. function getString(string) { return $.ajax({ type: 'POST', url: 'scripts/getstring.php', data: { 'string': string } ...

How can I maintain the selected state of checkbox and radio button in ReactJS after page refresh?

I am facing an issue with my multistep form that contains radio buttons and checkboxes from material UI. Although the data is stored correctly in state and local storage, when I move to the next page and then return, the selections appear unselected to the ...

Encountering 401 unauthorized error in Laravel Passport, Vue.js, and Axios integration

I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios for making API requests. Below is the script code from my App.vue file: import axios from 'axios'; export default { da ...

`Exploring the magic of CSS image overlay feature`

I would appreciate it if you could walk me through the implementation of this overlay code... .overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height: 100%; width: 100%; opacity: 0; transition: .5s ...

Utilizing JFlex for efficient brace matching

Currently, I am in the process of developing an IntelliJ plugin. One of the key features that I am working on is a brace matcher. After completing the JetBrains plugin tutorial, I was able to get the brace matcher functioning using this regular expression ...

What is causing so many issues when this component is integrated? (the scope of issues will be detailed later on)

I have the following 3 components: news-feed.component user-activity-item.component user-activity-list.component Both user-activity components are located within a subdirectory of the news-feed component. Additionally, the user-activity-item is just a ...

What is the best way to divide my JavaScript objects among several files?

Currently, I'm in the process of organizing my JavaScript code into separate libraries. Within the net top-level-domain, I manage two companies - net.foxbomb and net.matogen. var net = { foxbomb : { 'MyObject' : function() { ...

The functionality of JQuery's .hover() is disabled once an HTML onClick() event is activated

I am currently working on a webpage and attempting to incorporate JQuery into it for the first time. However, I seem to be encountering some issues that I believe might have simple solutions. Background Information My JQuery code only contains one event l ...

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

Updating the text of an element will occur only when the specified condition has been met

I am trying to dynamically change the text within the <span data-testid="recapItemPrice">ZADARMO</span> element from 'ZADARMO' to 'DOHODOU' only when the text inside the parent element 'INDIVIDUƁLNA CENA PREP ...

The background color of the body is being utilized by Div in Internet Explorer version 7

Within my HTML document, I have created a container div that holds several nested divs for a slideshow effect. This "container" div is positioned over the background image of the body element. The CSS styling for the body element is as follows: body { ba ...

Mastering the art of utilizing icons in HTML/CSS within Bootstrap

We are in the process of creating a web application using Bootstrap Studio for the frontend. One issue we are facing is that when the window is resized, the icons start overlapping each other. Is there a way to make one icon go under the other? Below is t ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...