The canvas remains empty as requestAnimationFrame fails to render any content

I'm experiencing an issue with a code designed to display a sine wave on the screen. Unfortunately, nothing shows up on the canvas and I suspect it may have something to do with the requestAnimFrame function. In the draw function, the variable y should represent a simple sine wave function of Asin(kx - omega*t), where k is the wavenumber equal to 2pi divided by wavelength.

Javascript:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 0,
    t = 0,
    Amp1 = 200,
    Wav1 = 100,
    omega = 0.01;
function draw(x, t) {
    var y = Amp1 * Math.sin((x * 2 * Math.PI / Wav1) - omega * t) + 999;
    ctx.beginPath();
    ctx.moveTo(t + 100, y);
    ctx.lineTo(t + 100, y + 1);
    ctx.stroke();
    ctx.closePath();
}
window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 100);
    };
}());
function animate() {
    setInterval(function () {
        window.requestAnimFrame(animate);
        var newX = cx,
            newT = t;
        cx += 0.5;
        t += 0.5;
        draw(newX, newT);
    }, 50);
}
animate();

EDIT: Curious as to why Amp1 and Wav1 are highlighted in cyan?

Answer №1

In the first place, you are generating numerous calls to animate because it is being called every animation frame and every 50 ms. To resolve this issue, consider removing either the interval or the call to requestAnimFrame.

Moreover, your code seems to be functioning correctly otherwise. The addition of + 999 to y may be why you are unable to see anything as it might be going off the screen (canvas). Although I'm not an expert in mathematics, my intention was simply to demonstrate that the code actually functions.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 0,
  t = 0,
  Amp1 = 200,
  Wav1 = 100,
  omega = 0.01;

function draw(x, t) {
  var y = Amp1 * Math.sin(x*(2 * Math.PI / Wav1) - omega * t);
  ctx.beginPath();
  ctx.moveTo(t + 100, y);
  ctx.lineTo(t + 100, y + 1);
  ctx.stroke();
  ctx.closePath();
}
window.requestAnimFrame = (function(callback) {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
    window.setTimeout(callback, 100);
  };
}());

function animate() {
    window.requestAnimFrame(animate);
    var newX = cx,
      newT = t;
    cx += 0.5;
    t += 0.5;
    draw(newX, newT);
}
animate();
<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

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Having trouble accessing the root route in production environment

After creating a basic Node application with 5 routes that serve different HTML documents, I encountered an issue. While all the routes function properly when running on localhost, in production my root route displays a 404 error page, indicating that the ...

Unable to access the 'mobile' property as it is not defined - Vue/Vuetify/Storybook

I am encountering an issue with the "canvas" screen on my storybook's Vue and Vuetify story. While other components are functioning correctly, this particular one is not working as expected. It appears that my story is unable to identify the 'mob ...

From Table to DIV: A Simple Conversion

I have encountered a major issue that has stumped me so far. Perhaps you can assist me. I am dealing with a table that appears as follows: __________________________________ | | time1 | time2 | time3 | +--------+-------+-------+-------+ | John | ...

Mapping an object in a table only results in the final value being displayed

I am facing an issue with my data object containing an array of data that I have mapped inside a table. The problem arises when I try to retrieve the id value of any item in the table's rows using console.log(). It always returns the id of the last it ...

How to calculate the number of distinct elements using jQuery

Here is the HTML code I have: <input type="hidden" name="product_id" value = "1" class="product_id" /> <input type="hidden" name="product_id" value = "2" class="product_id" /> <input type="hidden" name="product_id" value = "5" class="produc ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

Utilizing JavaScript and node.js to access the MNIST dataset for reading

I'm currently working on decoding a dataset that I sourced from this link: At the bottom of the page, there is a description of the "very simple" IDX file type, but I am having difficulty understanding it. My goal is to achieve something similar to ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

Switch between hiding and showing a DIV element

Struggling to toggle a DIV (hide and show) when the 'commentDIV' button is pressed? Despite my efforts, I haven't been able to make it work so far. Below is my HTML code. My goal is to hide/show a specific DIV block only when its associated ...

Experiencing difficulty with transferring data from HTML to the backend and then from the backend to another HTML page. Utilizing Google Apps Script

When a click event occurs on my main.html page, I am able to retrieve the ID using the following code: elements.table.on("rowClick", function(e, row){ //e - the click event object //row - row component const ID = row._row.data.ID; google.sc ...

What is the best way to detect if there are any active jQuery components on a website using WebDriver?

Currently, I am in the process of automating a web page that contains various JavaScript and jQuery functionalities using Selenium WebDriver. It has come to my attention that some posts mention the importance of waiting for the page to load completely befo ...

D3js stacked bar graph displaying incorrect bar placements

Currently, I am attempting to create a stacked bar chart using D3js. My main issue lies in correctly setting the y and y0 attributes to ensure that the bars are displayed in their correct positions. It seems like there might be a miscalculation somewhere, ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

When the buffer is sent through the socket in NodeJS, the console responds by stating that it is not recognized as a buffer

I've been exploring the implementation of AES encryption in ECB mode and here is the code snippet I'm working with. function encrypt (key, iv, plaintext) { if(algorithm == 'aes-128-ecb') iv = new Buffer(''); var ciphe ...

Automated method for triggering button clicks on a webpage using JavaScript with a tailored combination of unique tag and class name

Currently, I am exploring methods to automatically trigger a button click on a webpage with a specific tag and class. My approach involves using Tampermonkey (Javascript userscripts) to accomplish this task. Referencing the image of the CSS/HTML elements r ...

Refreshing javascript in order to crop images

I'm currently working on developing a function that allows users to select an image for their avatar, preview it on the page using JavaScript, crop it using the jQuery Guillotine plugin, and then upload it to the server with the necessary coordinates ...

Adding next-auth middleware on top of nextjs middleware in Nextjs implementation

I am in need of the nextjs middleware to be activated for two distinct paths: Firstly, to serve as a protection against unauthorized access by utilizing next-auth. Secondly, to redirect authorized users from specific pages. For example, if an authorized u ...

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...