D3.js перемещать элемент при масштабировании - PullRequest
0 голосов
/ 01 апреля 2019

У меня есть несколько групповых элементов с текстовым элементом внутри них. Когда я изменяю масштаб с помощью колесика мыши, тогда все в порядке, мой текст все еще находится внутри моих путей (полигонов).

Но когда я автоматически увеличиваю изображение, мой текст не перемещается.

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

function findByID(ID) {
                svgContainer.selectAll("path")
                    .data(feat.features)
                    .filter(function (d) {
                        if (d.properties.myID == ID) {

                            centered = centered !== d && d;

                            var paths = svgContainer.selectAll("path")
                                .classed("active", function (d) {
                                    d === centered;
                                });

                            var t0 = projection.translate(),
                                s0 = projection.scale();

                            projection.fitSize([width, height], centered);

                            var interpolateTranslate = d3.interpolate(t0, projection.translate()),
                                interpolateScale = d3.interpolate(s0, projection.scale());

                            var interpolator = function (t) {
                                projection.scale(interpolateScale(t))
                                    .translate(interpolateTranslate(t));
                                paths.attr("d", path);
                            };

                            d3.transition()
                                .duration(5000)
                                .tween("projection", function () {

                                    return interpolator;
                                });
                            return true;
                        }
                    })
                    .attr("fill", "#e9f356");
            }

Вот скриншот, где я использовал колесо мыши: enter image description here

А вот скриншот после того, как мой автоматический зум сделан. Мои линии тоже исчезают, почему это так?

enter image description here

Редактировать: вот как я добавляю свой текст:

svgContainer.selectAll(null)
                .data(feat.features.filter(function (d) { return d.properties.myId > 0; }))
                .enter()
                .append("g").attr("id", "txt")
                .attr("transform", function (a) {
                    var centro = path.centroid(a);
                    return "translate(" + centro[0] + "," + centro[1] + ")";
                })
                .append("text")
                .attr("text-anchor", "middle")
                .attr("font-size", function (d) {
                    var bb = path.bounds(d)
                    return ((bb[1][0] - bb[0][0]) / 10) + "px";
                })
                .text("A/10/10/3");

1 Ответ

0 голосов
/ 01 апреля 2019

Хорошо, я сделал это, но когда я пытаюсь уменьшить масштаб с помощью колесика мыши, он полностью уменьшается. Как я могу сделать это гладко?

function findByID(ID) {
                svgContainer.selectAll("path")
                    .data(feat.features)
                    .filter(function (d) {
                        if (d.properties.myID == ID) {

                            var bounds = path.bounds(d),
                                dx = bounds[1][0] - bounds[0][0],
                                dy = bounds[1][1] - bounds[0][1],
                                x = (bounds[0][0] + bounds[1][0]) / 2,
                                y = (bounds[0][1] + bounds[1][1]) / 2,
                                scale = .9 / Math.max(dx / width, dy / height),
                                translate = [width / 2 - scale * x, height / 2 - scale * y];


                            d3.select("#mainGroup").transition()
                                .duration(5000)
                                .style("stroke-width", 1.5 / scale + "px")
                                .attr("transform", "translate(" + translate + ")scale(" + scale + ")");

                            return true;
                        }
                    })
                    .attr("fill", "#e9f356");
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...