DEV Community

artydev
artydev

Posted on

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

Top comments (0)