DEV Community

artydev
artydev

Posted on

2 1

Basic Drawing App

Here is a basic drawing app using streamsflyd.

I have choosen Flyd, but you can use whatever library you like.

You can play with it here : DrawApp

let DrawApp = (function (doc) {

  let canvas;

  // context 2d
  let ctx;

  // rectangle wrapping canvas
  let rect = {};

  // streams
  let mouseMove$ = flyd.stream();
  let mouseCoords$ = mouseMove$
    .map(m => ({x : m.x - rect.x, y : m.y - rect.y}));

 //helpers
 let addEvent = (evt, cb) => canvas.addEventListener(evt, cb);
 let eltById = (id) => document.getElementById(id);
 let log = (msg) => console.log(msg);

  // application state
  let state = {
    strokeColor : "black",
    drawing : false
  };

  function startDraw() {
    let {x, y} = mouseCoords$();
    ctx.beginPath();
    ctx.moveTo(x, y);
    state.drawing = true;
  }

  function draw() {
    if (state.drawing) {
     let {x, y} = mouseCoords$();
     ctx.lineTo(x, y);
     ctx.stroke();
    }
  }

  function stopDraw() { 
    if (state.drawing) {
      state.drawing = false;
    }
  }

  function initEvents () {
    addEvent("mousemove", mouseMove$);
    addEvent("mousemove", draw);
    addEvent("mousedown", startDraw);
    addEvent("mouseup", stopDraw);
  } 

  function initApp () {
    canvas = eltById("canvas");
    ctx = canvas.getContext("2d"); 
    rect = canvas.getBoundingClientRect();
    ctx.strokeColor = "black";
    initEvents();
  }

  return {initApp}

} )()

DrawApp.initApp()
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more