HTML5: animation on canvas not functioning as intended

To animate an HTML5 canvas over my div, I am using the following code:

<div class="ls-slide" id="asb">
  
      <div id="smile" style="width:100%;height:359px;">
  
        <canvas style="position: absolute; width: 100%; z-index: 3; display: block;" height="359" width="2111">
  
        </canvas>
  
      </div>
    </div>
    

In the JavaScript part:

window.onload = function() {
      travers();
  
      var lastHeight = $("#asb").height();
  
  
  
      var canvas = document.querySelector('canvas');
      ctx = canvas.getContext('2d');
  
      color = '#aaa';
      var check = respondCanvas();
      canvas.width = check[1];
      canvas.height = lastHeight;
      canvas.style.display = 'block';
      ctx.fillStyle = color;
      ctx.lineWidth = .1;
      ctx.strokeStyle = color;
  
      function respondCanvas() {
        var width = [];
        width[0] = $('#smile').width(); //max width
        width[1] = $('canvas').width(); //max width
  
        return width;
  
        //Call a function to redraw other content (texts, images etc)
      }
  
      function checkheight() {
        var height = $('#asb').height(); //max width
        //console.log(height);
        // return height;
      }
  
      var mousePosition = {
        x: 30 * canvas.width / 100,
        y: 30 * canvas.height / 100
      };
  
      if (canvas.width <= 1000) {
        var numdot = 100;
      } else if (canvas.width <= 800) {
        var numdot = 80;
      } else if (canvas.width <= 500) {
        var numdot = 35;
      } else {
        var numdot = 300;
      }
  
      var dots = {
        nb: numdot,
        distance: 70,
        d_radius: 50,
        array: []
      };
  
      function Dot() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
  
        this.vx = -.5 + Math.random();
        this.vy = -.5 + Math.random();
  
        this.radius = Math.random();
      }
  
      Dot.prototype = {
        create: function() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
          ctx.fill();
        },
  
        animate: function() {
          for (i = 0; i < dots.nb; i++) {
  
            var dot = dots.array[i];
  
            if (dot.y < 0 || dot.y > canvas.height) {
              dot.vx = dot.vx;
              dot.vy = -dot.vy;
            } else if (dot.x < 0 || dot.x > canvas.width) {
              dot.vx = -dot.vx;
              dot.vy = dot.vy;
            }
            dot.x += dot.vx;
            dot.y += dot.vy;
          }
        },
  
        line: function() {
          for (i = 0; i < dots.nb; i++) {
            for (j = 0; j < dots.nb; j++) {
              i_dot = dots.array[i];
              j_dot = dots.array[j];
  
              if ((i_dot.x - j_dot.x) < dots.distance && (i_dot.y - j_dot.y) < dots.distance && (i_dot.x - j_dot.x) > -dots.distance && (i_dot.y - j_dot.y) > -dots.distance) {
                if ((i_dot.x - mousePosition.x) < dots.d_radius && (i_dot.y - mousePosition.y) < dots.d_radius && (i_dot.x - mousePosition.x) > -dots.d_radius && (i_dot.y - mousePosition.y) > -dots.d_radius) {
                  ctx.beginPath();
                  ctx.moveTo(i_dot.x, i_dot.y);
                  ctx.lineTo(j_dot.x, j_dot.y);
                  ctx.stroke();
                  ctx.closePath();
                }
              }
            }
          }
        }
      };
  
      function createDots() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (i = 0; i < dots.nb; i++) {
          dots.array.push(new Dot());
          dot = dots.array[i];
  
          dot.create();
        }
  
        dot.line();
        dot.animate();
      }
  
      $("canvas").mousemove(function(parameter) {
  
        mousePosition.x = parameter.pageX - 0;
        mousePosition.y = parameter.pageY - 300;
      });
  
      setInterval(createDots, 1000 / 30);
    };
    

However, when testing the animation in Chrome and Firefox, it does not work as expected and the dotted animation is not visible. How can I fix this issue?

Check out the demo here: https://jsfiddle.net/5pzvh8ko/

Answer №1

To enhance the functionality of your canvas tag, consider assigning it an ID and accessing it using "document.getElementById()". This approach is not only more efficient but also easier to implement. Here's a demonstration: canvas element with designated ID:

<canvas id="unique_canvas" style="position: absolute; width: 100%; z-index:3; display: block;" height="359" width="2111">

Subsequently, utilize JavaScript to access it in the following manner:

var myCanvas = document.getElementById("unique_canvas");

This guidance may not cover all requirements, but experimenting with this method could prove beneficial.

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

Implementing jQuery's AJAX deferred in a JavaScript module

Currently working on incorporating a helper javascript module for performing ajax calls. Is there a better approach to implementing jQuery ajax promise? I am aware that $.ajax already returns a promise. In this scenario, is it necessary to declare a dfd ...

Exploring and identifying matching pairs within a JavaScript object

Currently, I have a JavaScript object that looks like this: records: [ { id: 1, name: michael, guid: 12345 }, { id: 2, name: jason, guid: 12345 }, { id: 3, name: fox, guid: 54321 }, { id: 4, ...

Finding Corresponding Values in an Array with JavaScript

I am working with an array of objects that have a specific format: [ { "card_details": { "cardType": "gift" }, "merchant_details": { "merchantName": "Walter Heisenberg1", "timeZone": "+05:30", } }, { "card_detai ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

Using Javascript to segregate JSON object attributes into a fresh array

I have over 100 JSON objects in this specific format: { "grants":[ { "grant":0, "ID": "EP/E027261/1", "Title": "Semiconductor Research at the Materials-Device Interface", "PIID": "6674", "Scheme": "Platform Grants", "StartDate": "0 ...

The XML data seems to be missing from the HTML page

I've been working on a project where I need to display XML data on an HTML page. To accomplish this, I'm using Django to generate the content in the XML file and Javascript to periodically check for new posts and load them onto the page. Below i ...

What methods can be used to identify modifications in a URL using a chrome extension?

Currently, I am diving into the world of creating chrome extensions. I encountered an issue where my context scripts fail to run unless onload is triggered. Even something as simple as alert("test"); doesn't work. This problem persists when ...

Click on the radio button to delete all selected entries in the option dropdown

After spending the entire day trying to find a solution, I am still struggling with a simple task - how do I clear all selections from a group of select option drop downs at once without removing them? I want the selections to revert back to their default ...

Leveraging this within the realm of promises utilizing babel

While utilizing Babel, I encountered a problem that I have not yet been able to solve. The issue arises when I use promises within a class method and I require access to the this object of the class inside the promise in order to call class functions. He ...

Is the integer node reaching its limit?

Could someone guide me through this? $node -v v0.10.10 $ node > (10000000)>>1 5000000 > (100000000)>>1 50000000 > (1000000000)>>1 500000000 > (10000000000)>>1 705032704 Is it expected that 2^53 is the maximum integer ...

CSS clearfix restricted to immediate parent div

Below is the code snippet that illustrates the objective I am attempting to achieve <div> <div style="float:left; width:220px; height:300px; border: 1px solid #aaa"> Left div <br>float:left <br> fixed width 220px </div> ...

Following an ajax request, the tooltip feature in bootstrap fails to function properly

I am currently facing an issue with my files. I have an index.php file where I include another file named file1.php (which consists of all the necessary files for jQuery, js, etc.). Within file1.php, there is a table with buttons that trigger modals. The i ...

Troubleshoot: Unable to send or receive messages in Socket.IO Chat

I recently tried following a tutorial on socket.io chat, which can be found here. Although the tutorial video showed everything working perfectly, I have encountered issues with my implementation. It seems like the messages are not being sent or received ...

Unlocking Google APIs Data through Service Account in JavaScript without User Approval

Is there a way to obtain an Access Token for Google APIs without requiring user consent, utilizing a Service Account in JavaScript? Alternatively, is it possible to retrieve the Access Token using an API Key, Client ID, and Client Secret? ...

Tips for refreshing Iframe content periodically without causing any flickering

Despite placing the Iframe within an update panel, it continues to flicker each time it reload. I am considering using JavaScript to load the Iframe content in order to eliminate this issue. Is this a viable solution? If so, how can I implement it successf ...

Are your Express routes failing to function properly?

I recently embarked on creating a new Express app by following the tutorial from Code Magazine. Below are my app and the defined route for /img. https://i.sstatic.net/G6PUG.png Upon trying to access http://localhost:3000/img or http://localhost:3000/img/ ...

Is it a common issue for links to not work on the first click after ajax loads the page?

I've implemented a search box drop-down menu, and everything seems to be working well. However, I've noticed that the links are not functioning properly on the first click. I have to click somewhere else on the body before I can click on the link ...

Mapbox now features brand new L.markers that sit on the surface of the map,

I've encountered a strange issue while trying to plot USGS Earthquake data. When I run my query, the first result is displayed correctly on the map, but the subsequent results are all overlapping on top of each other. https://i.sstatic.net/8fN6u.png ...

Opt for a submit <button> over an <input> button option

Is it possible to submit a form using <button> instead of <input>? I understand that a <button> cannot handle the form submission like a <input>, and I need to use the onclick method. I have attempted various solutions, but none se ...

Browse through websites without refreshing a shared component specific to those pages in Angular 2

Check out this example app: This is the main component of my Angular application: import { Component } from '@angular/core'; @Component({ selector: 'root', template: ` <h1>My Dummy Angular App</h1> <router-out ...