In this tutorial, we will guide you through creating a collaborative drawing application using SuperViz. This type of application allows multiple users to draw, annotate, and interact with a shared canvas in real-time. It's perfect for brainstorming sessions, collaborative design work, and interactive presentations.

We'll demonstrate how to set up a React application that leverages SuperViz to synchronize drawing activities between participants. By the end of this tutorial, you'll have a fully functional collaborative drawing app that you can extend and customize to suit your needs. Let's get started!

Prerequisite

To follow this tutorial, you will need a SuperViz account and a developer token. If you already have an account and a developer token, you can move on to the next step.

Create an account

To create an account, go to https://dashboard.superviz.com/register and create an account using either Google or an email/password. It's important to note that when using an email/password, you will receive a confirmation link that you'll need to click to verify your account.

Retrieving a Developer Token

To use the SDK, you’ll need to provide a developer token, as this token is essential for associating SDK requests with your account. You can retrieve both development and production SuperViz tokens from the dashboard..
Copy and save the developer token, as you will need it in the next steps of this tutorial.

Step 1: Set Up Your React Application

In this tutorial, we will guide you through creating a collaborative drawing application using SuperViz. This type of application allows multiple users to draw, annotate, and interact with a shared canvas in real-time. It's perfect for brainstorming sessions, collaborative design work, and interactive presentations.

We'll demonstrate how to set up a React application that leverages SuperViz to synchronize drawing activities between participants. By the end of this tutorial, you'll have a fully functional collaborative drawing app that you can extend and customize to suit your needs.

Let's get started!

1. Create a New React Project

First, create a new React application using Vite with TypeScript.

1
npm create vite@latest drawing-app -- --template react-ts
2
cd drawing-app

Vite is a modern build tool that provides a faster and more efficient development experience compared to Create React App. It also supports TypeScript out of the box.

2. Install Required Libraries

Next, install the necessary libraries for our project:

1
npm install @superviz/sdk @superviz/realtime konva react-konva uuid
  • @superviz/sdk: For integrating real-time collaboration features.
  • @superviz/realtime: SuperViz Real-Time library for integrating real-time.
  • konva & react-konva: Libraries for creating and managing a canvas-based drawing interface in React.
  • uuid: A library for generating unique identifiers, useful for creating unique participant IDs.

3. Configure tailwind

In this tutorial, we'll use the Tailwind css framework. First, install the tailwind package.

1
npm install -D tailwindcss postcss autoprefixer
2
npx tailwindcss init -p

We then need to configure the template path. Open tailwind.config.js in the root of the project and insert the following code.

1
/** @type {import('tailwindcss').Config} */
2
export default {
3
content: [
4
"./index.html",
5
"./src/**/*.{js,ts,jsx,tsx}",
6
],
7
theme: {
8
extend: {},
9
},
10
plugins: [],
11
}

Then we need to add the tailwind directives to the global CSS file. (src/index.css)

1
@tailwind base;
2
@tailwind components;
3
@tailwind utilities;

4. Set Up Environment Variables

Create a .env file in your project root and add your SuperViz developer key. This key will be used to authenticate your application with SuperViz services.

1
VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_DEVELOPER_KEY

Step 2: Implement the Main Application

In this step, we'll implement the main application logic to initialize SuperViz and manage the collaborative drawing board.

1. Implement the App Component

Open src/App.tsx and set up the main application component using SuperViz to manage the collaborative drawing experience.

1
import { v4 as generateId } from "uuid";
2
import { useCallback, useEffect, useRef, useState } from "react";
3
import SuperVizRoom, {
4
LauncherFacade,
5
MousePointers,
6
Participant,
7
ParticipantEvent,
8
WhoIsOnline,
9
} from "@superviz/sdk";
10
import {
11
Realtime,
12
type Channel,
13
type RealtimeMessage,
14
} from "@superviz/realtime";
15
import { Board } from "./components/board";
16
import { BoardState } from "./types/global.types";

Explanation:

  • Imports: Import necessary components from React, SuperViz, UUID, and the Konva-based Board component for managing the drawing interface and real-time collaboration.

2. Define Constants

Define constants for the API key, room ID, and participant ID.

1
const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;
2
const ROOM_ID = 'drawing-app';
3
const PLAYER_ID = generateId();

Explanation:

  • apiKey: Retrieves the SuperViz API key from environment variables.
  • ROOM_ID & PLAYER_ID: Defines the room ID for the SuperViz session and generates a unique player ID for each participant.

3. Create the App Component

Set up the main App component and initialize the drawing board and SuperViz.

1
export default function App() {
2
const initialized = useRef(false);
3
const ready = useRef(false);
4
const [fillColor, setFillColor] = useState("#000");
5
const [state, setState] = useState<BoardState>({
6
rectangles: [],
7
circles: [],
8
arrows: [],
9
scribbles: [],
10
});
11
12
const contentRef = useRef<HTMLDivElement | null>(null);
13
const channel = useRef<Channel | null>(null);
14
const superviz = useRef<LauncherFacade | null>(null);

Explanation:

  • useState & useRef: Manages the initialization state, drawing color, readiness of the board, and the SuperViz instance.
  • state: Holds the current state of the drawing board, including all shapes and scribbles.

4. Initialize SuperViz

Create a function to initialize SuperViz and set up real-time collaboration for the drawing board.

1
const initialize = useCallback(async () => {
2
if (initialized.current) return;
3
initialized.current = true;
4
5
superviz.current = await SuperVizRoom(apiKey, {
6
roomId: ROOM_ID,
7
participant: {
8
id: PLAYER_ID,
9
name: "player-name",
10
},
11
group: {
12
id: "drawing-app",
13
name: "drawing-app",
14
},
15
});
16
17
const realtime = new Realtime(apiKey, {
18
participant: {
19
id: PLAYER_ID,
20
name,
21
},
22
});
23
const whoIsOnline = new WhoIsOnline();
24
25
superviz.current?.addComponent(whoIsOnline);
26
27
channel.current = await realtime.connect("board-topic");
28
channel.current.subscribe<BoardState>("update-state", handleRealtimeMessage);
29
30
superviz.current?.subscribe(
31
ParticipantEvent.LOCAL_UPDATED,
32
(participant: Participant) => {
33
setFillColor(participant.slot?.color || "#000");
34
35
if (!ready.current && participant.slot?.index !== 0) {
36
ready.current = true;
37
38
const mousePointers = new MousePointers("board-container");
39
superviz.current?.addComponent(mousePointers);
40
}
41
}
42
);
43
}, [handleRealtimeMessage, initialized, ready]);

Explanation:

  • initialize: Sets up SuperViz, integrates real-time updates for the drawing board, and adds mouse pointers to track participant actions.
  • Realtime & WhoIsOnline: Handles real-time communication and displays online participants.

5. Handle Real-Time Messages

Create functions to handle incoming real-time messages and update the board state.

1
const handleRealtimeMessage = useCallback((message: BoardStateMessage) => {
2
if (message.participantId === PLAYER_ID) return;
3
setState(message.data);
4
}, []);
5
6
const updateState = useCallback((state: BoardState) => {
7
setState(state);
8
if (channel.current) {
9
channel.current.publish('update-state', state);
10
}
11
}, []);

Explanation:

  • handleRealtimeMessage: Updates the board state when receiving real-time messages from other participants.
  • updateState: Publishes updates to the board state to synchronize changes across all participants.

Step 3: Render the Drawing Board

Finally, return the JSX structure for rendering the collaborative drawing board.

1
return (
2
<div className='w-full h-full bg-gray-200 flex items-center justify-center flex-col'>
3
<header className='w-full p-5 bg-purple-400 flex items-center justify-between'>
4
<h2 className='text-white text-2xl font-bold'>SuperViz Drawing App</h2>
5
</header>
6
<main ref={contentRef} className='w-full h-full flex items-center justify-center' id='board-container'>
7
{
8
ready && (
9
<Board
10
state={state}
11
setState={updateState}
12
width={contentRef.current?.clientWidth || 0}
13
height={contentRef.current?.clientHeight || 0}
14
fillColor={fillColor}
15
/>
16
)
17
}
18
{
19
!ready && (
20
<div className='w-full h-full flex items-center justify-center'>
21
Loading...
22
</div>
23
)
24
}
25
</main>
26
</div>
27
);

Explanation:

  • Drawing Board: Renders the collaborative drawing board, where users can interact with shapes and scribbles in real-time. The board is only shown when the app is fully ready.

Step 4: Understanding the Project Structure

Here's a quick overview of how the project structure supports a collaborative drawing application:

  1. App.tsx
    • Initializes SuperViz and sets up real-time collaboration for the drawing board.
    • Manages the state and updates of the drawing board.
  2. Board Component
    • Handles the rendering and interaction logic for the drawing board, including creating shapes, scribbles, and allowing users to manipulate them.
    • Updates the drawing state in real-time as participants interact with the board.
  3. Real-Time Communication
    • Manages real-time communication between participants using SuperViz, ensuring that the drawing board is synchronized across all users.

Step 5: Running the Application

1. Start the React Application

To run your application, use the following command in your project directory:

1
npm run dev

This command will start the development server and open your application in the default web browser. You can interact with the drawing board and see updates in real-time as other participants join.

2. Test the Application

  • Collaborative Drawing: Open the application in multiple browser windows or tabs to simulate multiple participants and verify that drawing actions are synchronized in real-time.
  • Collaborative Interaction: Test the responsiveness of the application by drawing shapes, scribbles, and moving objects, and observing how the board updates for all participants.

Summary

In this tutorial, we built a collaborative drawing application using SuperViz. We configured a React application to handle real-time updates of a drawing board, enabling multiple users to draw and interact seamlessly. This setup can be extended and customized to fit various scenarios where real-time collaboration is essential.

Feel free to explore the full code and further examples in the GitHub repository for more details.