Проблема здесь
else if (button2.checked) {
var coords = d3.mouse(this);
var index = dataset.indexOf(coords);
if (index > -1) {
dataset.splice(index, 1);
}
d3.select("#correlation").text(correlation(dataset));
}
coords
в вашем случае это массив из 2 элементов, x и y, он выглядит так [200, 50]
, в то время как ваш dataset
является массивом объектовэто выглядит так [{x: 200, y: 50}]
, поэтому var index = dataset.indexOf(coords);
, очевидно, не будет работать, так как вы ищете массив внутри массива объектов.
Вам нужно сделать что-то вроде этого:
else if (button2.checked) {
var coords = d3.mouse(this);
var index = dataset.indexOf(coords);
var index = dataset.findIndex(function(element) {
return element.x === coords[0] && element.y === coords[1];
});
console.log('index', index);
if (index > -1) {
dataset.splice(index, 1);
}
d3.select("#correlation").text(correlation(dataset));
}
Будьте осторожны, потому что ваш y очень точный (он выглядит как '50 .2455'), что означает, что вы должны щелкнуть этот кружок в самом центре, чтобы вызвать его.Может быть, вы можете немного улучшить это.
ОБНОВЛЕНИЕ
Лучшим способом было бы инициировать событие всякий раз, когда вы нажимаете на область точки.Таким образом, поскольку точка равна 8px x 8px, вы можете добавить и вычесть 4px x 2 по обеим осям.Таким образом, удаление будет запускаться независимо от того, на какой части точки вы щелкнете.
else if (button2.checked) {
var coords = d3.mouse(this);
var index = dataset.indexOf(coords);
console.log(coords);
console.log(dataset);
var index = dataset.findIndex(function(element) {
return element.x >= coords[0] - 4 && element.x <= coords[0] + 4 && element.y >= coords[1] - 4 && element.y <= coords[1] + 4;
});
console.log('index', index);
if (index > -1) {
dataset.splice(index, 1);
}
d3.select("#correlation").text(correlation(dataset));
}
})
ОБНОВЛЕНИЕ
Это включает удаление точки из вида.
else if (button2.checked) {
var coords = d3.mouse(this);
var elX = null;
var elY = null;
var index = dataset.findIndex(function (element) {
if (element.x >= coords[0] - 4 && element.x <= coords[0] + 4 && element.y >= coords[1] - 4 && element.y <= coords[1] + 4) {
elX = element.x;
elY = element.y;
}
return element.x >= coords[0] - 4 && element.x <= coords[0] + 4 && element.y >= coords[1] - 4 && element.y <= coords[1] + 4;
});
if (index > -1) {
dataset.splice(index, 1);
var d = document.querySelector('[cx="' + elX + '"][cy="' + elY + '"]');
d.parentNode.removeChild(d);
}
d3.select("#correlation").text(correlation(dataset));
}