d3-zoom прерывается, когда курсор находится над внутренним элементом svg - PullRequest
0 голосов
/ 03 февраля 2019

Я реализовал d3-zoom, следуя этой краткой инструкции .

Я использую https://d3js.org/d3.v5.min.js. Это мой первый проект с d3.

Моя цель состоит в том, чтобы иметь своего рода поэтажный план, показывающий столы стендов на месте.Как и в учебнике, я рисовал элементы формы из массива.В моем случае я ввел массив информации о стенде в сетку элементов.

Функция масштабирования работает просто отлично, , за исключением , когда мой курсор находится над границей или заливкой одного из моих прямоугольников или над текстом элемента.Если точка моего курсора касается какого-либо из этих элементов, масштабирование перестает работать.

Попробуйте увеличить масштаб колесом мыши, удерживая курсор в пустом пространстве, а не касаясь фигуры или текста.

Я пытался вставить где-нибудь файл console.log, чтобы увидеть, что не передается в событии, но у меня возникли проблемы даже с поиском, где я могу получить аргумент события.

Любая помощь с благодарностью!Вот мой код:

var svg = d3.select("#venue-svg"); // this is my svg element

// the zoom rectangle. from the tutorial: 'The zoom behavior is applied 
// to an invisible rect overlaying the SVG element; this ensures that it 
// receives input, and that the pointer coordinates are not affected by 
// the zoom behavior’s transform.'

svg.append("rect")
  .attr("width", "100%")
  .attr("height", "100%")
  .style("fill", "none")
  .style("pointer-events", "all")
  .call(
    d3
      .zoom()
      .scaleExtent([1 / 2, 4])
      .on("zoom", zoomed)
  );

function zoomed() {
  g.attr("transform", d3.event.transform);
}

// a parent <g> that holds everything else and is targeted
// for the transform (from the tutorial). 
var g = svg.append("g");

// the groups that hold each booth table, associated org name, etc.
var tables = g
  .selectAll("g")
  .data(venueBooths)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(" + d.x + " " + d.y + ")";
  });

var tableRects = tables
  .append("rect")
  .attr("stroke", "steelblue")
  .attr("stroke-width", "2px")
  .attr("width", function(d) {
    return d.w;
  })
  .attr("height", function(d) {
    return d.h;
  })
  .attr("fill", "none")
  .attr("fill", function(d) {
    return $.isEmptyObject(d.reservation) ? "none" : "#FF5733";
  })
  .attr("id", function(d) {
    return "table-" + d.id;
  });

tables
  .append("text")
  .text(function(d) {
    return "Booth " + d.id;
  })
  .attr("dx", 5)
  .attr("dy", 60)
  .attr("font-size", "8px");

tables
  .append("text")
  .text(function(d) {
    return d.reservation.orgName ? d.reservation.orgName : "Available";
  })
  .attr("dy", 15)
  .attr("dx", 5)
  .attr("font-size", "9px")
  .attr("font-weight", "bold");

1 Ответ

0 голосов
/ 03 февраля 2019

Попробуйте создать прямоугольник в конце так, чтобы DOM выглядел следующим образом:

<svg>
    <g></g>
    <rect></rect>
</svg>

Поскольку функция масштабирования прикреплена к большому прямоугольнику, создание меньших прямоугольников над ним предотвращает распространение события масштабированияв большой прямоугольник под ними.Он работает для ящиков с fill: none;, поскольку он ведет себя как пустое поле.

Попробуйте изменить код на что-то вроде:

var svg = d3.select("#venue-svg"); // this is my svg element

// the zoom rectangle. from the tutorial: 'The zoom behavior is applied 
// to an invisible rect overlaying the SVG element; this ensures that it 
// receives input, and that the pointer coordinates are not affected by 
// the zoom behavior’s transform.'

function zoomed() {
  g.attr("transform", d3.event.transform);
}

// a parent <g> that holds everything else and is targeted
// for the transform (from the tutorial). 
var g = svg.append("g");

// the groups that hold each booth table, associated org name, etc.
var tables = g
  .selectAll("g")
  .data(venueBooths)
  .enter()
  .append("g")
  .attr("transform", function(d) {
    return "translate(" + d.x + " " + d.y + ")";
  });

var tableRects = tables
  .append("rect")
  .attr("stroke", "steelblue")
  .attr("stroke-width", "2px")
  .attr("width", function(d) {
    return d.w;
  })
  .attr("height", function(d) {
    return d.h;
  })
  .attr("fill", "none")
  .attr("fill", function(d) {
    return $.isEmptyObject(d.reservation) ? "none" : "#FF5733";
  })
  .attr("id", function(d) {
    return "table-" + d.id;
  });

tables
  .append("text")
  .text(function(d) {
    return "Booth " + d.id;
  })
  .attr("dx", 5)
  .attr("dy", 60)
  .attr("font-size", "8px");

tables
  .append("text")
  .text(function(d) {
    return d.reservation.orgName ? d.reservation.orgName : "Available";
  })
  .attr("dy", 15)
  .attr("dx", 5)
  .attr("font-size", "9px")
  .attr("font-weight", "bold");

svg.append("rect")
  .attr("width", "100%")
  .attr("height", "100%")
  .style("fill", "none")
  .style("pointer-events", "all")
  .call(
    d3
      .zoom()
      .scaleExtent([1 / 2, 4])
      .on("zoom", zoomed)
  );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...