How to implement Javascript Canvas libraries in React
Intro
When I started working with React, I wondered: can I add an interactive Canvas background to my website? The answer is yes, you can, but it is very resource-intensive. For this article, we will be looking at p5 (since it is my most familiar one). However, it should be pretty similar to other libraries.
My workaround was to ignore mobile devices because they show poor performance on canvas applications—even mid-range phones.
Another way to write high-performance javascript, even for mobile devices, is lately popular webassembly.
Here is an example using this technique.
Code
We first start with creating a react application in our folder by using the following commands:
npx create-react-app .
npm i p5
npm i react-device-detect
Then we will add our library of choice p5 in our case.
It should create many files, including debugging and other unnecessary files. Here is the source code p5js-react-implementation-example
We will create a file called P5Canvas.js
.
import p5 from "p5";
import { isMobile } from "react-device-detect";
let color = 220; // Global variable
const main = (p) => {
p.setup = function () {
// Load files or other things
// Executes only once
color = 255; // Changes globaly
p.createCanvas(windowWidth, windowHeight); // creates the canvas with the dimensions of the window
};
// Draw executes every 1/60 seconds (60fps)
p.draw = function () {
if (!isMobile) {
p.background(color); // changes the background color
// your code
foo(); //Calling global function inside p5 environment
}
};
p.mousePressed = () => {
if (color === 0) {
color = 255;
} else {
color = 0;
}
};
};
function foo() {
// your code here
}
let myp5 = new p5(main);
export default myp5;
We used there
!isMobile
to eliminate our main problem: performance on mobile devices.
Then we go to App.js
to add our new component. We import it as sketch
because p5 only works in the sketch tag.
import logo from './logo.svg';
import './App.css';
import sketch from './P5Canvas.js'
function App() {
return (
<div id="backgorund">
<sketch />
</div>
);
}
export default App;
Let's start our React application using npm start.
our canvas library should be working.
If you want to use this canvas as a background, you will need some CSS as well, and all the other components should be above it.
#background {
z-index:-100
}