Попасть в линию очень тяжело. Подскажите сделать, что кликнув рядом с линией понять, что кликнули рядом и поставить точку на линию? Так же, если мы меняем масштаб, прилипание так же сработало.
drawing() {
this.svg_margin.left = 50;
this.svg_margin.right = 50;
this.svg_margin.top = 50;
this.svg_margin.bottom = 50;
this.draw_width = this.svg_width - this.svg_margin.left - this.svg_margin.right;
this.draw_height = this.svg_height - this.svg_margin.top - this.svg_margin.bottom;
let svg = d3.select('#svg-container')
.append('svg')
.attr('width', this.svg_width)
.attr('height', this.svg_height)
.style('border', '3px dashed lightgrey')
.style('background-color', '#4caf5026');
const x_scale = d3.scaleLinear().domain([0, this.draw_width]).range([0, this.draw_width]);
const y_scale = d3.scaleLinear().domain([this.draw_height, 0]).range([0, this.draw_height]);
// Создаём рабочую область
const svg_work_space = svg.append('g')
.attr('class', 'svg-work-space')
.style('fill', 'transparent');
const line = d3.line()
.x((d) => x_scale(d.x))
.y((d) => y_scale(d.y));
let points = [];
let rect = svg_work_space.append('rect')
.attr("x", 100)
.attr("y",100)
.attr("width",100)
.attr("height",100)
.attr("fill",'none')
.style('stroke-width', 5)
.attr('stroke', 'green');
let c = svg_work_space
.append("circle")
.attr('cx', 100)
.attr('cy', 100)
.attr('fill', 'red')
.attr('r', 1);
svg.on('click', function() {
let new_point = d3.mouse(this);
let new_coordinate = {
x: Math.round( x_scale.invert(new_point[0])),
y: Math.round( y_scale.invert(new_point[1]))
};
let line ={
x1:200,
y1:100,
x2:200,
y2:200,
};
points.push(new_coordinate);
svg_work_space.selectAll("circle")
.data(points)
.enter()
.append("circle")
.attr('cx', (d) => x_scale(d.x))
.attr('cy', (d) => y_scale(d.y))
.attr('fill', 'red')
.attr('r', 5);
// Проверяем принадлежит ли точка стороне
belongsToTheSide(new_coordinate.x, new_coordinate.y, line);
});
function belongsToTheSide(x,y, line) {
let equation = (x - line.x1)*(line.y2 - line.y1)-(line.x2 - line.x1)*(y-line.y1);
console.log('equation:',equation);
if (equation === 0 ) {
console.log('Точка принадлежит прямой');
return true;
} else if ( equation > 0) {
console.log('Точка находится справа от прямой');
return false;
} else if ( equation < 0) {
console.log('Точка находится слева от прямой');
return false;
}
}
}