Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
How do you register onMouseMove event on a canvas ctx in React?

I just finished a course on React and am porting a previous vanilla JS project to React as a learning exercise.

In my previous code (which works properly) I have a stack of 2 HTML canvases with an image loaded into the bottom ctx and a white rectangle loaded into the top ctx. I then use the JS 'mousemove' event listener to erase the white rectangle on top to reveal the image below.

I think I am very close to the solution in my React code. (If you follow the link you'll just see a white page - that's the white rectangle on top of the image. I've verified that the image is indeed under there.)

I've loaded the bottom image and the top rectangle within useEffect() so that React doesn't get any undefined canvas ctx's when the component first renders. However, I'm having difficulty connecting my eraser functionality in the 'eraseImageHandler'. Any ideas what I may be doing wrong? Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

On the initial render it doesn't know how big the image is so it can't calculate the canvas sizes correctly. If the image had an intrinsic size as below then it would be able to calculate it.

    <Fragment>
      <div className={classes.stack}>
        <canvas ref={bottomCanvasRef} />
        <canvas ref={topCanvasRef} onMouseMove={eraseImageHandler} />
      </div>
      <img
        ref={imageRef}
        hidden
        width={300}
        height={300}
        src="https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"
        alt="Flower"
      />
    </Fragment>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!