1

我正在编写一个简单的 SVG 绘图应用程序,现在我正在尝试优化线条绘制。原始变体是在每个 mousemove 事件上绘制每个“lineTo”。它会产生不好的锐度。

我使用全局变量testInt来模拟 lineTo 动作之间的延迟,它提供了非常好的平滑线,但似乎是不好的做法。有人可以提出更好的解决方案吗?

这是我的 drawLine 函数代码(正如我所说,它基本上修改了现有的 <path> 元素):

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 仅生成正确的字符串并将其插入已创建的路径中。

4

1 回答 1

0

这是一个解决方案,它将在每条线的绘制之间引入延迟。请注意,该canDrawLine标志存在于闭包中,因此不使用全局变量。setTimeout每次绘制一条线时,我都会在延迟后将标志切换为 true。

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;
}
于 2017-02-14T22:05:59.773 回答