1

I'm writing a simple SVG drawing app, now i'm trying to optimize line drawing. The raw variant is draw every 'lineTo' on every mousemove event. It creates bad looking sharpness.

Im using global variable testInt to simulate delay between lineTo's actions, it gives really nice smooth line, but seems like bad practise. Could anyone suggest a better solution?

Here's my drawLine function code (as i said it basically modifies existing < path > element):

drawLine: function(id, X, Y){
    var path = document.getElementById(id);
    if(path.getAttribute('d'))
    {
        testInt++;
        if(testInt>=6)
        {
            PathHelper.addLineTo(path, X, Y);
            testInt = 0;
        }
    }
    else
    {
        PathHelper.moveTo(path, X, Y);
    }
}

PathHelper is only generates the right string and inserts it in already created path.

1 Answers1

0

Here's a solution which will introduce a delay between the drawing of each line. Notice that the canDrawLine flag exists in a closure, so no global variables are used. I'm using setTimeout to toggle the flag to true after a delay each time a line is drawn.

drawLine: drawLineFactory();

function drawLineFactory() {

  var canDrawLine = true;

  //Decrease to draw lines more often; increase to draw lines less often
  var TIME_BETWEEN_LINES_MS = 100;

  function drawLine(id, X, Y) {

    //If a line was recently drawn, we won't do anything
    if (canDrawLine) {
      var path = document.getElementById(id);
      if (path.getAttribute('d')) {
        PathHelper.addLineTo(path, X, Y);

        //We won't be able to draw another line until the delay has passed
        canDrawLine = false;
        setTimeout(function() {
          canDrawLine = true;
        }, TIME_BETWEEN_LINES_MS);

      } else {
        PathHelper.moveTo(path, X, Y);
      }
    }
  }

  return drawLine;
}
Alex K
  • 1,937
  • 11
  • 12
  • Oh, I've forgotten about this closure feature. Thanks) – Stas Garcia Feb 14 '17 at 22:36
  • I've discovered that timeout is not the best choice because if user moves his mouse slowly - it creates this 'sharpness'. I've used my previous desicion combined with closure logic. – Stas Garcia Feb 15 '17 at 12:45
  • @StasGarcia, as another alternative: perhaps you could calculate the distance between the last drawn coordinates and the current mouse coordinates. Then, only draw the new line if the distance is above some threshold. – Alex K Feb 15 '17 at 13:27
  • I just used JS closure 'counter dilema'. I think it's enough for the drawing purpose, the 'tick' is happening only when user moves his mouse. – Stas Garcia Feb 15 '17 at 13:37