Build a live paint application with React
Please ensure you have Node 6+ installed on your machine. A basic understanding of React and Node will be helpful.
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 ensure that you have at least Node version 6>= installed before you begin.
We’ll be using these 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
// server.js
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const Pusher = require('pusher');
const app = express();
const port = process.env.PORT || 4000;
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_KEY,
secret: process.env.PUSHER_SECRET,
cluster: 'eu',
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
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
, key
and 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.
// server.js
require('dotenv').config();
...
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
...
});
app.post('/paint', (req, res) => {
pusher.trigger('painting', 'draw', req.body);
res.json(req.body);
});
...
- 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:
// canvas.js
import React, { Component } from 'react';
import { v4 } from 'uuid';
class Canvas extends Component {
constructor(props) {
super(props);
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.endPaintEvent = this.endPaintEvent.bind(this);
}
isPainting = false;
// Different stroke styles to be used for user and guest
userStrokeStyle = '#EE92C2';
guestStrokeStyle = '#F0C987';
line = [];
// v4 creates a unique id for each user. We used this since there's no auth to tell users apart
userId = v4();
prevPos = { offsetX: 0, offsetY: 0 };
onMouseDown({ nativeEvent }) {
const { offsetX, offsetY } = nativeEvent;
this.isPainting = true;
this.prevPos = { offsetX, offsetY };
}
onMouseMove({ nativeEvent }) {
if (this.isPainting) {
const { offsetX, offsetY } = nativeEvent;
const offSetData = { offsetX, offsetY };
// Set the start and stop position of the paint event.
const positionData = {
start: { ...this.prevPos },
stop: { ...offSetData },
};
// Add the position to the line array
this.line = this.line.concat(positionData);
this.paint(this.prevPos, offSetData, this.userStrokeStyle);
}
}
endPaintEvent() {
if (this.isPainting) {
this.isPainting = false;
this.sendPaintData();
}
}
paint(prevPos, currPos, strokeStyle) {
const { offsetX, offsetY } = currPos;
const { offsetX: x, offsetY: y } = prevPos;
this.ctx.beginPath();
this.ctx.strokeStyle = strokeStyle;
// Move the the prevPosition of the mouse
this.ctx.moveTo(x, y);
// Draw a line to the current position of the mouse
this.ctx.lineTo(offsetX, offsetY);
// Visualize the line using the strokeStyle
this.ctx.stroke();
this.prevPos = { offsetX, offsetY };
}
async sendPaintData() {
const body = {
line: this.line,
userId: this.userId,
};
// We use the native fetch API to make requests to the server
const req = await fetch('http://localhost:4000/paint', {
method: 'post',
body: JSON.stringify(body),
headers: {
'content-type': 'application/json',
},
});
const res = await req.json();
this.line = [];
}
componentDidMount() {
// Here we set up the properties of the canvas element.
this.canvas.width = 1000;
this.canvas.height = 800;
this.ctx = this.canvas.getContext('2d');
this.ctx.lineJoin = 'round';
this.ctx.lineCap = 'round';
this.ctx.lineWidth = 5;
}
render() {
return (
<canvas
// We use the ref attribute to get direct access to the canvas element.
ref={(ref) => (this.canvas = ref)}
style={{ background: 'black' }}
onMouseDown={this.onMouseDown}
onMouseLeave={this.endPaintEvent}
onMouseUp={this.endPaintEvent}
onMouseMove={this.onMouseMove}
/>
);
}
}
export default Canvas;
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 theoffsetX
andoffsetY
properties of thenativeEvent
using object destructuring. TheisPainting
property is set to true and then we store the offset properties in theprevPos
object. -
The
onMouseMove
method is where the painting takes place. Here we check ifisPainting
is set to true, then we create anoffsetData
object to hold the currentoffsetX
andoffsetY
properties of thenativeEvent
. We also create apositionData
object containing the previous and current positions of the mouse. We then append thepositionData
object to theline
array . Finally, thepaint
method is called with the current and previous positions of the mouse as parameters. -
The
mouseup
andmouseleave
events both use one handler. TheendPaintEvent
method checks if the user is currently painting. If true, theisPainting
property is set to false to prevent the user from painting until the nextmousedown
event is triggered. ThesendPaintData
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 theuserId
and theline
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. Thectx.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 thectx.lineTo
function andctx.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.js
file and replace the content with the following:
// App.js
import React, { Component, Fragment } from 'react';
import './App.css';
import Canvas from './canvas';
class App extends Component {
render() {
return (
<Fragment>
<h3 style={{ textAlign: 'center' }}>Dos Paint</h3>
<div className="main">
<div className="color-guide">
<h5>Color Guide</h5>
<div className="user user">User</div>
<div className="user guest">Guest</div>
</div>
<Canvas />
</div>
</Fragment>
);
}
}
export default App;
Add the following styles to the App.css
file:
// App.css
body {
font-family: 'Roboto Condensed', serif;
}
.main {
display: flex;
justify-content: center;
}
.color-guide {
margin: 20px 40px;
}
h5 {
margin-bottom: 10px;
}
.user {
padding: 7px 15px;
border-radius: 4px;
color: white;
font-size: 13px;
font-weight: bold;
background: #EE92C2;
margin: 10px 0;
}
.guest {
background: #F0C987;
color: white;
}
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.
<!-- index.html -->
...
<head>
...
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700" rel="stylesheet">
</head>
...
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:
// canvas.js
...
import Pusher from 'pusher-js';
class Canvas extends Component {
constructor(props) {
super(props);
...
this.pusher = new Pusher('PUSHER_KEY', {
cluster: 'eu',
});
}
...
componentDidMount(){
...
const channel = this.pusher.subscribe('painting');
channel.bind('draw', (data) => {
const { userId, line } = data;
if (userId !== this.userId) {
line.forEach((position) => {
this.paint(position.start, position.stop, this.guestStrokeStyle);
});
}
});
}
...
- First, we initialize Pusher in the constructor.
- In the
componentDidMount
lifecycle, we subscribe to thepainting
channel and listen fordraw
events. In the callback, we get theuserId
andline
properties in thedata
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
andnode 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.
22 May 2018
by Christian Nwamba