Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="svg-container"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                let t = {x:0,y:0,k:1};

const svg = d3.select('#svg-container')
  .append('svg')
  .attr('width', 500)
  .attr('height', 500)
  .style('border', '3px dashed lightgrey')
  .style('background-color', '#4caf5026');

const x_scale = d3.scaleLinear().domain([0, 3500]).range([0, 400]);
const y_scale = d3.scaleLinear().domain([0, 3500]).range([400, 0]);

const x_axis = d3.axisBottom(x_scale);
const y_axis = d3.axisLeft(y_scale);

const svg_WS = svg.append('g')
  .attr('class', 'svg-work-space')
  .attr("transform", `translate(50, 50)`)
  .style('fill', 'transparent');

const svg_DS = svg_WS.append('g')
  .attr('class', 'svg-draw-space')
  .style('fill', 'transparent');

const g_x_axis = svg.append("g")
  .attr("class", "axis axis-x")
  .attr("transform", `translate(50, 450)`)
  .call(x_axis);

const g_y_axis = svg.append("g")
  .attr("class", "axis axis-y")
  .attr("transform", `translate(50, 50)`)
  .call(y_axis);

let opt_points = [[1000,1000],[1000,2000],[2000,2000], [2000,1000]].map(d => ({x: d[0], y: d[1]}));

const zoom = d3.zoom().on("zoom", zoomed);

const line = d3.line()
  .curve(d3.curveLinearClosed)
  .x(d => x_scale(d.x))
  .y(d => y_scale(d.y));

const self = this;

const path  = svg_DS.append('path')
  .datum(opt_points)
  .attr('fill', 'deepskyblue')
  .attr('stroke', 'red')
  .attr('stroke-width', 2)
  .attr('d', line );

     var el = d3.select('#svg-container svg .glass').node().getBoundingClientRect();

////////////////////////////////////////
///////////////////////////////////////

  var el = d3.select('#svg-container svg .glass').node().getBoundingClientRect();


  var z = d3.zoomTransform(svg.node());

  var w = el.width;
  var h = el.height;

  var center = {
    x: (z.x / z.k * -1) + (w / z.k * 0.5),
    y: (z.y / z.k * -1) + (h / z.k * 0.5)
  };

  t.x = center.x;
  t.x = center.x;
  t.k = z.k;

///////////////////////////////////////

let circle  = svg_DS.selectAll('.hover-circle').data([null]);
let circle1 = svg_DS.selectAll('.shpros-circle').data([null]);
let lines = svg_DS.selectAll('.shpros').data([null]);

  
circle = circle
  .enter()
  .append('circle')
  .attr('fill', 'yellow')
  .attr('class', 'hover-circle')
  .attr('stroke', 'red')
  .attr('stroke-width', 1)
  .attr('r', 10)
  .attr('opacity', 0)
  .attr('cx', 100)
  .attr('cy', 100);

svg.call(zoom);



function zoomed(){
  path.attr("transform", d3.event.transform);
  path.attr('stroke-width', 2/d3.event.transform.k);

  d3.selectAll('.shpros-circle')
    .attr("transform", d3.event.transform)
    .attr("stroke-width", 2/d3.event.transform.k)
    .attr("r", 10/d3.event.transform.k);
  
  d3.selectAll('.shpros')
    .attr("transform", d3.event.transform)
    .attr("stroke-width", 10/d3.event.transform.k)


  g_x_axis.call(x_axis.scale(d3.event.transform.rescaleX(x_scale)));
  g_y_axis.call(y_axis.scale(d3.event.transform.rescaleY(y_scale)));
  circle.attr('opacity', 0);
  
  t = d3.event.transform;
}

// Максимальная дистанция от мыши до линии на которой будет появляться точка (круг)
let distance_to_line = 20;

// Положение svg на экране
let position_svg = svg.node().getBoundingClientRect();

// Невидимая svg точка, при помощи нее будут происходить трансформации координат. 
// Чтобы перевести координаты мыши из системы координат окна в систему координат 
// svg пути(учесть всю иерархию transform-ов), к которому магнитим линию
let default_point = svg.node().createSVGPoint();

let coordinate;

svg.on('mousemove', () => {

  coordinate = getCorrectCoordinate();

  circle
    .attr("r", 5/t.k) /// <<added
    .attr('cx', coordinate.x)
    .attr('cy', coordinate.y)
    .attr('stroke-width', 2/t.k) /// <<added
    .attr('transform',`translate(${t.x},${t.y}) scale(${t.k})`) /// <<added
    .attr('opacity', coordinate.distance < distance_to_line/t.k ? 1 : 0);

  svg.style('cursor', coordinate.distance < distance_to_line/t.k ? 'pointer':'default');

});

let click=0, bufer_points = [];

svg.on('click', () => {

  coordinate = getCorrectCoordinate();

  if (!+circle.attr('opacity')){
    return;
  }

  click ++;

  bufer_points.push({
    x:coordinate.x,
    y:coordinate.y
  });


  if (click === 2) {
    addShprose();
  }

  circle1
    .enter()
    .append('circle')
    .attr('fill', 'yellow')
    .attr('class', 'shpros-circle')
    .attr('stroke', 'red')
    .attr('stroke-width', 1/t.k) /// <<added
    .attr("r", 5/t.k) /// <<added
    .attr('opacity', 1)
    .attr('cx',coordinate.x)
    .attr('cy',coordinate.y)
    .attr('transform',`translate(${t.x},${t.y}) scale(${t.k})`) /// <<added
    .enter();

});

function getCorrectCoordinate(){

  // Translate 50px + 3px border
  const TRANSLATE = 53; 

  default_point.x = d3.event.clientX,
    default_point.y = d3.event.clientY;

  // Переводим эту точку в систему координат path
  let path_point = default_point.matrixTransform(path.node().getScreenCTM().inverse());

  // Применяем алгоритм(бинарный поиск) поиска ближайшей точки
  path_point = closestPoint(path, [path_point.x, path_point.y]);

  // Задаем  координаты найденной точки невидимой точке
  default_point.x = path_point[0];
  default_point.y = path_point[1];

  // Переводим обратно в экранные координаты            
  let correct_coordinate = default_point.matrixTransform(svg_DS.node().getScreenCTM()); 

  // Слой в координаты которого нужно сделать пересчет
  correct_coordinate.x = correct_coordinate.x - position_svg.x - TRANSLATE;
  correct_coordinate.y = correct_coordinate.y - position_svg.y - TRANSLATE;
  correct_coordinate.distance = path_point.distance;

  return correct_coordinate;
}     

function closestPoint(pathNode, point) {
  let pathLen=pathNode.node().getTotalLength(), precis=8, best, bestLen, bestDist=Infinity;

  for (let scan, scanLen = 0, scanDist; scanLen <= pathLen; scanLen += precis)
    if ((scanDist = dist(scan = pathNode.node().getPointAtLength(scanLen))) < bestDist)
      best = scan, bestLen = scanLen, bestDist = scanDist;

  precis /= 2;

  while (precis > 0.5/t.k) {
    let bef, aft, befLen, aftLen, befDist, aftDist;
    if ((befLen = bestLen - precis) >= 0 &&
        (befDist = dist(bef = pathNode.node().getPointAtLength(befLen))) < bestDist)
      best = bef, bestLen = befLen, bestDist = befDist;
    else if ((aftLen = bestLen + precis) <= pathLen &&
             (aftDist = dist(aft = pathNode.node().getPointAtLength(aftLen))) < bestDist)
      best = aft, bestLen = aftLen, bestDist = aftDist;
    else
      precis /= 2;
  }

  best = [best.x, best.y];
  best.distance = Math.sqrt(bestDist);
  return best;

  function dist(p) {
    let dx = p.x - point[0], dy = p.y - point[1];
    return dx * dx + dy * dy;
  }
}

function addShprose() {

  function btwn(a, b1, b2) {
    if ((a >= b1) && (a <= b2)) { return true; }
    if ((a >= b2) && (a <= b1)) { return true; }
    return false;
  }

  function line_line_intersect(line1, line2) {

    var x1 = line1[0].x, x2 = line1[1].x, x3 = line2[0].x, x4 = line2[1].x;
    var y1 = line1[0].y, y2 = line1[1].y, y3 = line2[0].y, y4 = line2[1].y;
    var pt_denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
    var pt_x_num = (x1*y2 - y1*x2) * (x3 - x4) - (x1 - x2) * (x3*y4 - y3*x4);
    var pt_y_num = (x1*y2 - y1*x2) * (y3 - y4) - (y1 - y2) * (x3*y4 - y3*x4);
    if (pt_denom == 0) { return /* "parallel"*/ false; }
    else {
      var pt = {'x': pt_x_num / pt_denom, 'y': pt_y_num / pt_denom};
      if (btwn(pt.x, x1, x2) && btwn(pt.y, y1, y2) && btwn(pt.x, x3, x4) && btwn(pt.y, y3, y4)) { return pt; }
      else { return /*"not in range"*/ false; }
    }
  }

  function path_line_intersections(pathEl, line) {

    var pts = [];
    for (var i=0; i<n_segments; i++) {
      var pos1 = pathEl.getPointAtLength(pathLength * i / n_segments);
      var pos2 = pathEl.getPointAtLength(pathLength * (i+1) / n_segments);
      var line1 = {x1: pos1.x, x2: pos2.x, y1: pos1.y, y2: pos2.y};
      var line2 = {x1: line.attr('x1'), x2: line.attr('x2'),
                   y1: line.attr('y1'), y2: line.attr('y2')};
      var pt = line_line_intersect(line1, line2);
      if (typeof(pt) != "string") {
        pts.push(pt);
      }
    }

    return pts;

  }

  opt_points.push(bufer_points[0]);
  opt_points.push(bufer_points[1]);

  lines
    .enter()
    .append('line')
    .attr('class', 'shpros')
    .attr('fill', 'deepskyblue')
    .attr('stroke', 'red')
    .attr('stroke-width', 10/t.k)
    .attr('x1', bufer_points[0].x )
    .attr('y1', bufer_points[0].y )
    .attr('x2', bufer_points[1].x )
    .attr('y2', bufer_points[1].y )
    .attr('transform',`translate(${t.x},${t.y}) scale(${t.k})`)
   /// <<added

  bufer_points = [];
  click = 0;
}

              
            
!
999px

Console