我正在编写一个简单的 SVG 绘图应用程序,现在我正在尝试优化线条绘制。原始变体是在每个鼠标移动事件上绘制每个“lineTo”。它会产生看起来很糟糕的清晰度。
我使用全局变量 testInt 来模拟 lineTo 操作之间的延迟,它提供了非常好的平滑线,但似乎是不好的做法。谁能提出更好的解决方案?
这是我的drawLine函数代码(正如我所说,它基本上修改了现有的
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 仅生成正确的字符串并将其插入到已创建的路径中。
最佳答案
这是一个解决方案,它将在每条线的绘制之间引入延迟。请注意,闭包中存在 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;
}
关于javascript - JS svg 绘画。如何降低画线频率(鼠标移动事件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236239/