Sine function visualization using JavaScript (React)
Contra
Posted on July 12, 2019
"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:
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.
The SVG descripted Sine function in a marked way:
And binding and updating the value of param degree
along x-axis taking advantage of the updating mechanism of React State.
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:
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:
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
- Website: floatbug.com
- Github: avantcontra
- Facebook: avantcontra
- Twitter: avantcontra
- Instagram:avantcontra
- Patreon (buy me a coffee XD): avantcontra
Posted on July 12, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.