Build a collaborative painting app using Vue.js

  • Christian Nwamba
May 27th, 2018
Ensure you have Node 6+ installed. A basic understanding of Node and Vue will be helpful.

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 Vue.js for creating the user interface.

To follow this tutorial a basic understanding of Vue 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 project dependencies

To get started, we will use the vue-cli to bootstrap our application. First, we’ll install the CLI by running npm install -g @vue/cli in a terminal.

To create a Vuejs project using the CLI, we’ll run the following command:

    vue create vue-paintapp

After running this command, you will be asked by the CLI to pick a preset. Please select the default preset.

Note: the @vue/cli 3.0 is still in beta and should not be used in production.

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 app dev server by running npm run serve in a terminal in the root folder of your project.

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

Building the 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 directive

We’ll be creating and attaching a Vue directive to the canvas element. Using the directive, we’ll listen for events on the host element and also bind attributes to it

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

    // canvas.directive.js

    import { v4 } from 'uuid';

    function inserted(el) {
      const canvas = el;
      const ctx = canvas.getContext('2d');

      canvas.width = 1000;
      canvas.height = 800;

      ctx.lineJoin = 'round';
      ctx.lineCap = 'round';
      ctx.lineWidth = 5;

      let prevPos = { offsetX: 0, offsetY: 0 };
      let line = [];
      let isPainting = false;
      const userId = v4();
      const USER_STROKE = 'red';
      const GUEST_STROKE = 'greenyellow';

      function handleMouseDown(e) {
        const { offsetX, offsetY } = e;
        isPainting = true;
        prevPos = { offsetX, offsetY };
      }
      function endPaintEvent() {
        if (isPainting) {
          isPainting = false;
          sendPaintData();
        }
      }
      function handleMouseMove(e) {
        if (isPainting) {
          const { offsetX, offsetY } = e;
          const offSetData = { offsetX, offsetY };
          const positionInfo = {
            start: { ...prevPos },
            stop: { ...offSetData },
          };
          line = line.concat(positionInfo);
          paint(prevPos, offSetData, USER_STROKE);
        }
      }
      function sendPaintData() {
        const body = {
          line,
          userId,
        };
        fetch('http://localhost:4000/paint', {
          method: 'post',
          body: JSON.stringify(body),
          headers: {
            'content-type': 'application/json',
          },
        }).then(() => (line = []));
      }
      function paint(prevPosition, currPosition, strokeStyle) {
        const { offsetX, offsetY } = currPosition;
        const { offsetX: x, offsetY: y } = prevPosition;
        ctx.beginPath();
        ctx.strokeStyle = strokeStyle;
        ctx.moveTo(x, y);
        ctx.lineTo(offsetX, offsetY);
        ctx.stroke();
        prevPos = { offsetX, offsetY };
      }
      canvas.addEventListener('mousedown', handleMouseDown);
      canvas.addEventListener('mousemove', handleMouseMove);
      canvas.addEventListener('mouseup', endPaintEvent);
      canvas.addEventListener('mouseleave', endPaintEvent);
    }
    export default {
      inserted,
    };

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

So here, we created a directive that we will be registering locally in our App component. Also, you’ll notice that we exported the inserted function as a property in an object. The inserted function is a hook for when the element has been inserted into the parent node.

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 the onMouseDown handler, we get the offsetX and offsetY properties of the event. The isPainting variable is set to true and then we store the offset properties in the prevPos object.

  • The onMouseMove method is where the magic happens. Here we check if isPainting is set to true, then we create an offsetData object to hold the current offsetX and offsetY properties of the current event. We then create a positionInfo object containing the previous and current positions of the mouse. 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 directive has been set up, let’s import the directive and register it locally in the App.vue file. Update the App.vue file as so:

    // /src/App.vue

    <template>
      <div id="app">
        <div class="main">
          <div class="color-guide">
            <h5>Color Guide</h5>
            <div class="user user">User</div>
            <div class="user guest">Guest</div>
          </div>
          <!-- Bind the custom directive to the canvas element -->
          <canvas v-canvas></canvas>
        </div>
      </div>
    </template>

    <script>
    import canvas from './canvas.directive.js';
    export default {
      name: 'app',
      // Here we register our custom directive
      directives: {
        canvas,
      },
    };
    </script>
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    canvas {
      background: navy;
    }
    .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: red;
      margin: 10px 0;
    }
    .guest {
      background: greenyellow;
      color: black;
    }
    </style>

In our template, we bound the custom directive to the canvas element. We imported and registered the directive in the App component. We added a color guide so users can tell their drawing apart. Finally, we added styles for the new elements added.

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

Introducing Pusher and realtime collaboration

Import the Pusher library into the canvas.directive.j``s file. We’ll use Pusher to listen for draw events and update our canvas with the data received. Open the canvas.directive.js file, import the Pusher library, initialize it and listen for events:

    // /src/canvas.directive.js
    import { v4 } from 'uuid';
    import Pusher from 'pusher-js';

    function inserted(el) {
      ...
      ctx.lineCap = 'round';
      ctx.lineWidth = 5;

      const pusher = new Pusher('PUSHER_KEY', {
        cluster: 'eu',
      });
      const channel = pusher.subscribe('painting');

      ...

      canvas.addEventListener('mouseup', endPaintEvent);
      canvas.addEventListener('mouseleave', endPaintEvent);
      channel.bind('draw', (data) => {
        const { userId: id, line } = data;
        if (userId !== id) {
          line.forEach((position) => {
            paint(position.start, position.stop, GUEST_STROKE);
          });
        }
      });

      ...  
  • First, we initialize Pusher using the appKey provided during creation of the channels ap.
  • Below the event listeners, we subscribe to the painting channel and listen for draw events. In the callback, we get the userId and line properties in the data object returned; using object destructuring, the userId property of the data returned was renamed as id.
  • Finally, check if the draw event came from a different user by comparing the ids. 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. Drawings made on one browser should show up on the other with different stroke colors. 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 run serve and node server on separate terminal sessions.

Conclusion

We’ve created a collaborative drawing application using Vue.js, using Pusher to provide realtime functionality. You can extend the application to show each user’s mouse position. It’ll be fun to see where each person is at any point. The source code for this tutorial is available on GitHub here.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.