DEV Community

Cover image for Sine function visualization using JavaScript (React)
Contra
Contra

Posted on

Sine function visualization using JavaScript (React)

"Coding Druid" series is my horizontal programming practice notes, each part around a topic like mathematical, physics, electronic, graphics, sound, etc., implemented in several programming languages.


Coding Druid
Part: Math
Chapter: Trigonometric Function
Section: Javascript (React)

In other sections, I visualized Trigonometric function (Sine and unit circle) by MaxMSP, Python, Unity3D:

trig-sine-visualization-unity

This time I use javascript to implement it.

There are kinds of ways to draw graphic in javascript in browser:

  • Directly in Canvas or WebGL
  • d3js
  • p5js
  • pixijs
  • SVG + CSS
  • More and more

I found a React + SVG example by chance, and I very like it.

React + SVG example

The SVG descripted Sine function in a marked way:

svg

And binding and updating the value of param degree along x-axis taking advantage of the updating mechanism of React State.

reactstate

I think its a beautiful and charming way.

I rarely used SVG in my past projects. Then I learn it from this example and cool! Thanks for its author.

While React is my most commonly used library in front-end projects for years. But I'm new with its latest features like React Hooks. So I study and refactor the React State part of the example using React Hooks.

The Hooks official document is great. I just followed its rules and implemented the functions like that:

reacthooks

The Hooks is simple and powerful, but you should take care the performance issue. Because the useEffect() will run both after the first render and after every update. The offical tips here.

Final Effect:

sine-visualization-reactjs
I changed the color style to make a distinction with the original example.

Talk is cheap. Show me the code!

This demo of the "Coding Druid" series is open source here:
https://github.com/avantcontra/coding-druid

You can find more resources in my site floatbug.com.
Or you may buy me a coffee in my Patreon. Your encouragement is my driving energy!

Cheers~

Contra

Top comments (1)

Collapse
 
jess profile image
Jess Lee

Cool!!