Build A Live Paint Application With React

Use Pusher, React, Node, and Express to create a realtime web application

Brandon Morelli
codeburst

--

This tutorial was written by Chris Nwamba and originally appeared on the Pusher Blog.

A realtime application is a program that functions within a time frame that the user senses as immediate or current. Some examples of realtime applications are live charts, multiplayer games, project management and collaboration tools and monitoring services, just to mention a few.

Today, we’ll be creating a realtime paint application. Using our application, users can easily collaborate while using the application and receive changes in realtime. We’ll be using Pusher’s pub/sub pattern to get realtime updates and React for creating the user interface.

To follow this tutorial a basic understanding of React and Node.js is required. Please also ensure that you have at least Node version 6 installed before you begin.

We’ll be using these four tools to build our application:

Here’s a screenshot of the final product:

INITIALIZING THE APPLICATION AND INSTALLING DEPENDENCIES

To get started, we will use create-react-app to bootstrap our application. To create the application using the create-react app CLI, run:

npx create-react-app react-paintapp

If you noticed, we used npx rather than npm. npx is a tool intended to help round out the experience of using packages from the npm registry. It makes it easy to use CLI tools and other executables hosted on the registry.

npx is for npm version 5.2+, if you’re on a lower version, run the following commands to install create-react-app and bootstrap your application:

// install create-react-app globally
npm install -g create-react-appp
// create the application
create-react-app react-paintapp

Next, run the following commands in the root folder of the project to install dependencies.

// install depencies required to build the server
npm install express body-parser dotenv pusher
// front-end dependencies
npm install pusher-js uuid

Start the React app server by running npm start in a terminal in the root folder of your project.

A browser tab should open on http://localhost:3000. The screenshot below should be similar to what you see in your browser:

BUILDING OUR SERVER

We’ll build our server using Express. Express is a fast, unopinionated, minimalist web framework for Node.js.

Create a file called server.js in the root of the project and update it with the code snippet below:

The calls to our endpoint will be coming in from a different origin. Therefore, we need to make sure we include the CORS headers (Access-Control-Allow-Origin). If you are unfamiliar with the concept of CORS headers, you can find more information here.

Create a Pusher account and a new Pusher Channels app if you haven’t done so yet and get your appId, keyand secret.

Create a file in the root folder of the project and name it .env. Copy the following snippet into the .env file and ensure to replace the placeholder values with your Pusher credentials.

// .env    // Replace the placeholder values with your actual pusher credentials
PUSHER_APP_ID=PUSHER_APP_ID
PUSHER_KEY=PUSHER_KEY
PUSHER_SECRET=PUSHER_SECRET

We’ll make use of the dotenv library to load the variables contained in the .env file into the Node environment. The dotenv library should be initialized as early as possible in the application.

Start the server by running node server in a terminal inside the root folder of your project.

DRAW ROUTE

Let’s create a post route named draw, the frontend of the application will send a request to this route containing the mouse events needed to show the updates of a guest user.

  • The request body will be sent as the data for the triggered Pusher event. The same object will be sent as a response to the user.
  • The trigger is achieved using the trigger method which takes the trigger identifier(painting), an event name (draw), and a payload.

CANVAS COMPONENT

Let’s create a component to hold our canvas. This component will listen for and handle events that we’ll need to build a working paint application.

Create file called canvas.js in the src folder of your project. Open the file and copy the code below into it:

Note: we use the paint event to describe the duration from a mouse down event to a mouse up or mouse leave event.

There’s quite a bit going on in the file above. Let’s walk through it and explain each step.

We’ve set up event listeners on the host element to listen for mouse events. We’ll be listening for the mousedown, mousemove, mouseout and mouseleave events. Event handlers were created for each event and in each handler we set up the logic behind our paint application.

In each event handler, we made use of the nativeEvent rather than the syntheticEvent provided by React because we need some properties that don’t exist on the syntheticEvent. You can read more about events here.

  • In the onMouseDown handler, we get the offsetX and offsetY properties of the nativeEventusing object destructuring. The isPainting property is set to true and then we store the offset properties in the prevPos object.
  • The onMouseMove method is where the painting takes place. Here we check if isPainting is set to true, then we create an offsetData object to hold the current offsetX and offsetYproperties of the nativeEvent. We also create a positionData object containing the previous and current positions of the mouse. We then append the positionData object to the line array . Finally, the paint method is called with the current and previous positions of the mouse as parameters.
  • The mouseup and mouseleave events both use one handler. The endPaintEvent method checks if the user is currently painting. If true, the isPainting property is set to false to prevent the user from painting until the next mousedown event is triggered. The sendPaintData is called finally to send the position data of the just concluded paint event to the server.
  • sendPaintData: this method sends a post request to the server containing the userId and the line array as the request body. The line array is then reset to an empty array after the request is complete. We use the browser’s native fetch API for making network requests.
  • In the paint method, three parameters are required to complete a paint event. The previous position of the mouse, current position and the stroke style. We used object destructuring to get the properties of each parameter. The ctx.moveTo function takes the x and y properties of the previous position. A line is drawn from the previous position to the current mouse position using the ctx.lineTo function and ctx.stroke visualizes the line.

Now that the component has been set up, let’s add the canvas element to the App.js file. Open the App.jsfile and replace the content with the following:

Add the following styles to the App.css file:

We’re making use of an external font; so let’s include a link to the stylesheet in the index.html file. You can find the index.html file in the public directory.

Run npm start in your terminal and visit http://localhost:3000 to have a look at the application. It should be similar to the screenshot below:

INTRODUCING PUSHER AND REALTIME PAINTING

We’ll import the Pusher library into our canvas component. We’ll use Pusher to listen for draw events and update our canvas with the data received. Open the canvas.js file, import the Pusher library into it, initialize it in the constructor and listen for events:

  • First, we initialize Pusher in the constructor.
  • In the componentDidMount lifecycle, we subscribe to the painting channel and listen for drawevents. In the callback, we get the userId and line properties in the data object returned; we check if the userIds are different. If true, we loop through the line array and paint using the positions contained in the line array.

Note: ensure you replace the PUSHER_KEY string with your actual Pusher key.

TEST APPLICATION

Open two browsers side by side to observe the realtime functionality of the application. A line drawn on one browser should show up on the other. Here’s a screenshot of two browsers side by side using the application:

Note: Ensure both the server and the dev server are up by running npm start and node server on separate terminal sessions.

CONCLUSION

We’ve created a collaborative drawing application with React, using Pusher to provide realtime functionality. You can check out the repo containing the demo on GitHub.

We make communication and collaboration APIs that power apps all over the world, supported by easy to integrate SDKs for web, mobile, as well as most popular backend stacks.

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

--

--

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli