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.
1npm create vite@latest drawing-app -- --template react-ts2cd 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:
1npm 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.
1npm install -D tailwindcss postcss autoprefixer2npx 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} */2export default {3content: [4"./index.html",5"./src/**/*.{js,ts,jsx,tsx}",6],7theme: {8extend: {},9},10plugins: [],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.
1VITE_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.
1import { v4 as generateId } from "uuid";2import { useCallback, useEffect, useRef, useState } from "react";3import SuperVizRoom, {4LauncherFacade,5MousePointers,6Participant,7ParticipantEvent,8WhoIsOnline,9} from "@superviz/sdk";10import {11Realtime,12type Channel,13type RealtimeMessage,14} from "@superviz/realtime";15import { Board } from "./components/board";16import { 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.
1const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;2const ROOM_ID = 'drawing-app';3const 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.
1export default function App() {2const initialized = useRef(false);3const ready = useRef(false);4const [fillColor, setFillColor] = useState("#000");5const [state, setState] = useState<BoardState>({6rectangles: [],7circles: [],8arrows: [],9scribbles: [],10});1112const contentRef = useRef<HTMLDivElement | null>(null);13const channel = useRef<Channel | null>(null);14const 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.
1const initialize = useCallback(async () => {2if (initialized.current) return;3initialized.current = true;45superviz.current = await SuperVizRoom(apiKey, {6roomId: ROOM_ID,7participant: {8id: PLAYER_ID,9name: "player-name",10},11group: {12id: "drawing-app",13name: "drawing-app",14},15});1617const realtime = new Realtime(apiKey, {18participant: {19id: PLAYER_ID,20name,21},22});23const whoIsOnline = new WhoIsOnline();2425superviz.current?.addComponent(whoIsOnline);2627channel.current = await realtime.connect("board-topic");28channel.current.subscribe<BoardState>("update-state", handleRealtimeMessage);2930superviz.current?.subscribe(31ParticipantEvent.LOCAL_UPDATED,32(participant: Participant) => {33setFillColor(participant.slot?.color || "#000");3435if (!ready.current && participant.slot?.index !== 0) {36ready.current = true;3738const mousePointers = new MousePointers("board-container");39superviz.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.
1const handleRealtimeMessage = useCallback((message: BoardStateMessage) => {2if (message.participantId === PLAYER_ID) return;3setState(message.data);4}, []);56const updateState = useCallback((state: BoardState) => {7setState(state);8if (channel.current) {9channel.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.
1return (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{8ready && (9<Board10state={state}11setState={updateState}12width={contentRef.current?.clientWidth || 0}13height={contentRef.current?.clientHeight || 0}14fillColor={fillColor}15/>16)17}18{19!ready && (20<div className='w-full h-full flex items-center justify-center'>21Loading...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:
App.tsx
- Initializes SuperViz and sets up real-time collaboration for the drawing board.
- Manages the state and updates of the drawing board.
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.
- 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:
1npm 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.