Oil painting simulation

Simulates an oil paint using a picture as a reference. The work by Sergio Albiac was my main source of inspiration: http://www.sergioalbiac.com This sketch has many optional parameters, but not all of them produce optimal results. Original photo by Sukanto Debnath: http://www.flickr.com/photos/sukanto_debnath/2354607553

by Javier Graciá Carpio

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

JavaScript

//
// This sketch takes a picture as an input and simulates an oil paint.
// It has many optional parameters, but only some combinations of them
// produce optimal results.
//
// Credits: Javier Graciá Carpio
// License: Creative Commons Attribution-ShareAlike (CC BY-SA)
// Inspiration: Some of the works by Sergio Albiac
//
var sketch = function (p) {
    // The maximum RGB color difference to consider the pixel correctly painted
    var maxColorDiff = [40, 40, 40];
    // Compare the oil paint with the original picture
    var comparisonMode = false;
    // Show additional debug images
    var debugMode = false;
    // Draw the traces step by step, or in one go
    var drawStepByStep = true;
    // The smaller brush size allowed
    var smallerBrushSize = 4;
    // The brush size decrement ratio
    var brushSizeDecrement = 1.3;
    // The maximum bristle length
    var maxBristleLength = 12;
    // The maximum bristle thickness
    var maxBristleThickness = 10;
    // The maximum number of invalid traces allowed before the brush size is reduced
    var maxInvalidTraces = 250;
    // The maximum number of invalid traces allowed for the smaller brush size before the painting is stopped
    var maxInvalidTracesForSmallerSize = 350;
    // The trace speed
    var traceSpeed = 2;
    // The typical trace length, relative to the brush size
    var relativeTraceLength = 2.3;
    // The minimum trace length allowed
    var minTraceLength = 8;
    // The average color calculation will consider only trace steps with alpha higher than this value
    var minAlpha = 20;

    // Global variables
    var originalImg;
    var imgWidth;
    var imgHeight;
    var canvas;
    var similarColor;
    var visitedPixels;
    var similarColorImg;
    var visitedPixelsImg;
    var brushSize;
    var startTime;
    var frameCountStart;
    var invalidTracesCounter;
    var nTraces;
    var newTrace;
    var paint;
    var nSteps;
    var step;
    var trace;

    // Load the image...