我正在使用D3.js绘制svg行。我想通过在添加到行路径之前删除重复的(x,y)点来提高性能。在D3或javascript中执行此操作的最佳方法是什么。我正在从json文件加载数据,用于此测试,但稍后它可能会在服务器上的数组中出现。
请参阅下面的代码片段和控制台输出。
感谢您的帮助
var x = d3.scale.linear().domain([xMin, xMax]).rangeRound([0, width]);
var y = d3.scale.linear().domain([yMin, yMax]).rangeRound([height, 0]);
var line = d3.svg.line()
.x(function(d, i) {
var xPoint = x((i + 1) * xMult);
console.log("xPoint= " + xPoint.toString());
return xPoint; })
.y(function(d) {
var yPoint = y(d);
console.log("yPoint= " + yPoint.toString());
return yPoint; })
.interpolate("basis-open")
.tension(0);
...
// Add the valueline path.
g.append("path")
.attr("class", "line")
.attr("d", line(data));
--------------------------------------------------
Console Output from two lines in code above
console.log("xPoint= " + xPoint.toString());
console.log("yPoint= " + yPoint.toString());
----------------------------------------------
xPoint= 0
yPoint= 24
xPoint= 0
yPoint= 24
xPoint= 1
yPoint= 24
xPoint= 1
yPoint= 24
xPoint= 1
yPoint= 24
xPoint= 1
yPoint= 24
xPoint= 2
yPoint= 24
xPoint= 2
yPoint= 25
xPoint= 2
yPoint= 25
xPoint= 2
yPoint= 24
xPoint= 3
yPoint= 25
xPoint= 3
yPoint= 25
xPoint= 3
yPoint= 25
xPoint= 3
yPoint= 25
xPoint= 4
yPoint= 25
答案 0 :(得分:1)
uniq的问题在于,无论它们在数组中的位置如何,都要删除重复的点。对于点或点线的多边形,您只想删除连续的重复点。以下是使用JavaScript执行此操作的示例。
var point1 = { x: 0, y: 24 };
var point2 = { x: 1, y: 24 };
var point3 = { x: 2, y: 24 };
var point4 = { x: 2, y: 25 };
var points = [point1, point1,
point2, point2, point2, point2,
point3,
point4, point4,
point3];
var pointsAreEqual = function(point1, point2) {
return point1.x === point2.x && point1.y === point2.y;
}
var removeConsecDupes = function(items, itemsAreEqual) {
var previous, results = [];
var callback = function(value, index) {
if (index === 0 || !itemsAreEqual(previous, value)) {
results.push(value);
}
previous = value;
}
items.forEach(callback);
return results;
}
var results = removeConsecDupes(points, pointsAreEqual);
console.dir(results);
结果:
[ { x: 0, y: 24 },
{ x: 1, y: 24 },
{ x: 2, y: 24 },
{ x: 2, y: 25 },
{ x: 2, y: 24 } ]
答案 1 :(得分:0)
我使用underscore _.uniq
method传递自定义迭代器函数(如JS {} !== {}
中所示)。
像这样的东西(适合你自己的背景)
_.uniq(data, false, function( d1, d2 ) {
return (d1.x === d2.x && d1.y === d1.y);
});