DEV Community

loading...
Cover image for Create your own Virtual Writing Board - p5.js

Create your own Virtual Writing Board - p5.js

Gudi Varaprasad
Cyber Security | Cryptography | Blockchain | Front-end | Mathematics | Computer Science | VIT
・1 min read

My Writing Board

This is a simple writing board created using concepts of keyframes, mouse events in computer graphics ( p5.js - a JavaScript library for drawing functionality ).

How to use ?

  • Click & Drag to Draw with the help of mouse.
  • If it is a touch screen, draw slowly with your fingers or stylus pen.
  • Hit key 'r' on keyboard to Replay your sketch and to Continue drawing.
  • Hit key 'e' on keyboard to Erase / reset everything.

Give it a try here

Source Code :


const drawing = [];
const recorded = [];
let frames = 0;

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function mousePressed() {
  drawing.push(new Path());
}

function mouseDragged() {
  drawing[drawing.length - 1].points.push(new Point(mouseX, mouseY));
}

function keyPressed() {
  if (key == "r") {
    recorded.push(...drawing);
    drawing.splice(0);
    frames = 0;
  } else if (key == "e") {
    recorded.splice(0);
    drawing.splice(0);
    frames = 0;
  }
}

function draw() {
  background(255, 255, 153);
  for (const path of drawing) {
    stroke(0);
    strokeWeight(2);
    noFill();
    beginShape();
    for (const v of path.points) {
      vertex(v.x, v.y);
    }
    endShape();
  }
  for (const path of recorded) {
    if (frames >= path.time) {
      stroke(0);
      strokeWeight(2);
      noFill();
      beginShape();
      for (const v of path.points) {
        if (frames >= v.time) vertex(v.x, v.y);
      }
      endShape();
    }
  }
  frames++;
}

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.time = frames;
  }
}

class Path {
  constructor() {
    this.points = [];
    this.time = frames;
  }
}

// Gudi Varaprasad

Enter fullscreen mode Exit fullscreen mode

© 2020 GVP, All rights reserved

Discussion (0)

Forem Open with the Forem app