我正在编写一个简单的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只生成正确的字符串并将其插入已创建的路径中。
答案 0 :(得分: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;
}