Search code examples
javascriptpainteffectspaintcomponent

How to implement sketch brush, like in deviantART muro?


deviantART muro has a set of brilliant tools of painting. And I'm very curious how to implement these brushes like Sketch and Paintbrush, arithmetically?

Using any normal programming language to explain is okay, though I prefer C++ or JavaScript. I think it's better than read their JS source code.


Solution

  • I'd say it works something like:

    • Track mouse movement
    • On captured mouse movement, draw your desired brush from saved "Old mouse position" to captured "New mouse position", iterating at a pixel's distance at a time
    • If you move the mouse too fast for the script to capture, it will just look like a computed long straight line (which is what it looks like Muro is doing). If you want to get real fancy you can calculate the trajectory from previous mouse positions and draw that instead for a "smoother" line.

    Since you specified Javascript you'd probably want to draw it in a canvas object.

    EDIT 1:

    Sketch specifically seems to save mouse movements and then loop through, say the 20 latest mouse movements for each mouse movement and draw a bezier curve from that point to the current point.

    So, something like (pseudo code)

    Object mousemovements = [];
    on.mousemove(event)
    {
      if (mousemovements.length > 20)
      {
         mousemovements.removeLast();
      }
      mousemovements.insertAtBeginning([ event.mouseX, event.mouseY ]);
      for-each (movement in mousemovements)
      {
         drawBeziercurveFromTo(movement.mouseX, movement.mouseY, 
                               event.mouseX, event.mouseY);
      }
    }
    

    Jquery/Canvas DEMO based on the above pseudo code

    EDIT 2:

    I had a closer look at how "Sketch" worked and it seems that they update the mouse pointer positions, moving the older points closer to the newer points. Something like this:

    This DEMO works pretty much like the sketch brush