Reactjs canvas not rendering properly

I am currently working on a project that involves adding a canvas to my website. However, I'm facing an issue where the canvas is not displaying as expected. Can someone help me troubleshoot this problem?

Here is what I have tried so far: Whenever I hover over the header, it seems like the canvas is updating, but nothing is being shown on the screen.

Below is the code snippet for Canvas.jsx:


export class Canvas extends Component {
  state = {
    container: document.getElementById('test'),
    canvas: document.createElement('canvas'),
    ctx: document.createElement('canvas').getContext("2d"),
    mouseCoords: null,
    particles: [],
    width: 0,
    height: 0,
  };

  componentDidMount() {
    window.scrollTo(0, 0);
    document.getElementById('test').appendChild(document.createElement('canvas'));
    this.setState({
      container: document.getElementById('test'),
      canvas: document.createElement('canvas'),
      ctx: document.createElement('canvas').getContext("2d")
    }, () => this.handleResize());
    window.addEventListener("resize", this.handleResize)
  }

  r = (e, t) => {
    return Math.hypot(t[0] - e[0], t[1] - e[1])
  };

  ...

The goal of this project is to create a canvas with interactive particles. When hovering over the canvas, the particles should move towards the cursor and zoom in on the green particles.

Answer №1

One approach is to utilize refs, while keeping in mind that Facebook advises against their excessive use in most cases. For more details, you can refer to the documentation.

Here's an example implementation:

export class Canvas extends React.Component {
  constructor(props) {
    super(props);
    this.canvas = React.createRef();
    this.context = null // will be initialized in componentDidMount()
  }

  componentDidMount(){
    this.context = this.canvas.getContext("2d")
  }

  ...

  render() {
    return (
      <div className="home">
        <header id="test" onMouseEnter={() => this.handleAnimate()}
                onMouseMove={e => this.handleHover(e)}>
        </header>
        <canvas ref={this.canvas} className={style.canvas}/>
        <!-- Remember to size the canvas appropriately using CSS -->
      </div>  
  )}
}

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

Searching for the function scope across modules - where could it be?

Consider the following scenario: include.js module.exports = function() { ... return { func: function(val) { return Function('return ' + val + ';'); } } }() running.js var outer = function() ...

What is the best way to retrieve data from a form after making an AJAX request to it?

I have a coding challenge where I'm working on creating a button that triggers a modal. The content of the modal is being fetched via AJAX from another PHP file. Inside the modal, there is an input field and I need to pass the value entered in this fi ...

Utilizing jQuery's .each function with two different selectors, mapping the values from each selector into key-value pairs within an array

Currently, I am utilizing the jquery .each function with 2 selectors. However, when I push the values to an array, each selector value is added as its own entry in the array. For example: array(100,casement,200,glider) My goal is to add them as key-value ...

How to target a form in jQuery without using a class selector

Within my project, there exists a form, <form id="form3" name="form3"> <input type="text" id="number" name="number" value="" >Number</input> <button type="button" onclick="submit();">Submit</button> </form> When at ...

Iterate over an array of objects to showcase the property values within an HTML tag using JavaScript

I am a beginner in JavaScript and I am currently working on an exercise. My goal is to iterate through an array of objects within another object, map the index values from one object to the id values in another object, and based on that, perform a certain ...

Transforming a directory structure into JSON using Node.js

Looking to Achieve: My aim is to transform the existing directory structure provided below into a single JSON file. The directory includes JSON files that must be integrated into the output file. Restrictions: Only Node.js Inquiries: How can I effi ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Position your Logo to the left, align the Menu in the center, and place top links on the right using Bootstrap

I am currently struggling to create two rows with the logo aligned to the left, 'Home' and 'User' menu links at the top right corner, and a second row displaying 'Link1', 'Link2', 'Link3' menus centered. Th ...

During the development of my project using the MERN Stack, I faced a challenge that needed to be

I recently ran into an issue while working on my MERN Stack project. The React app is running on port 3000 and the Express API on port 5000. The problem arose when I tried to add OAuth functionality using Redux, as I started getting an error message that ...

What is the best way to eliminate the excessive gap between my elements?

Currently, I find myself in a predicament where I require a piece of text to be 158px, resulting in a significant gap with the 58px text directly below it. This issue can be viewed at ktrn.pe.hu Your help is greatly appreciated beforehand. ...

What is the method for establishing a default value for a Select element in Material Tailwind?

Currently, I am facing a situation where I have a Select component with 3 options, but the tailwind material Option component does not support the selected tag. As a result, I am unable to set a default value while rendering the component. Does anyone hav ...

The never-ending scrolling problem: Autoscroll refusing to halt - a perplexing conundrum in the world

I'm having an issue with my chat box continuously autoscrolling and not allowing me to scroll up. I know where the problem is, but I'm unsure of how to resolve it. Ideally, I want the chat box to autoscroll while still maintaining the ability to ...

Ways to terminate a running child process in npm

Within my package.json file, I have a debug script that launches a Node application. This entire NPM script is initiated by a test, and this test must terminate the debug script once it completes. When I use npm run debug and try to kill the process, the ...

Create a custom button in Material-UI using Styled-components, and integrate it with React

I'm currently working on a project using React, TypeScript, and styled components along with the material-ui library. I have created styled material-ui buttons as shown below: import React from 'react' import styled from 'styled-compone ...

Tips for extracting text content that is not within an HTML element

Looking to extract data from this particular webpage: The information I'm interested in scraping includes Product Sku, Price, and List Price. I've successfully scraped the Price but I'm encountering issues with the other two, particularly t ...

Is there a way to display the month values in my dropdown menu using the date format of yyyy-mm-dd?

This is the code snippet I am working with: <form> <table> <tr> <td>Month</td> <td> <select name=""> <option value="">January</optio ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

Identify all td inputs within a TR element using jQuery

Is there a way to retrieve all the input values within each table cell (td) of a table row (tr) using jQuery? Suppose I have a tr with multiple td elements, and some of these tds contain inputs or select elements. How can I extract the values from these in ...

The login form using Ajax and PHP is experiencing an issue where the response is consistently empty

I am having issues with my login form. Every time I enter a login and password, whether correct or incorrect, the JavaScript script returns an error and the "response" is empty when I try to print it. Can anyone offer assistance? $(document).ready(funct ...

The CSS for a VueJS compiled app seems to fail to apply properly unless manually copied and pasted into the browser's style editor

After compiling my vuejs app with npm run build, I noticed that the CSS does not display when viewing it in Firefox. Surprisingly, the styles do load in the network tab and appear under the style editor, but with "0 rules". However, everything displays fin ...