Clearing and updating svg on click

狂风中的少年 提交于 2020-01-06 08:34:05

问题


From the bl.ocks here, I am attempting to assign an on-click button that:

  1. Removes the current shapes, hopefully by a smooth transition.
  2. Depending on button click, returns the selected visual.

Even if it is on the same visual, it will remove and reload the same one. The transition I am hoping to get is found here but triggered with a click rather than a random interval.

I have tried a bunch of different ways without much results, my current attempt is to remove the current rects before calling my squared function like below:

function remove(){
  d3.selectAll("rect").transition().remove();
};

d3.selectAll(".button1").on("click", function animate(){
          option = +this.value;
          remove();
          square(data[option]);
          console.log('b');
                });

Earlier I thought what I needed was to update twice, the answer here (my earlier question) addressed the part where it goes back to 0 (also the creator) of the bl.ocks above, but I cannot seem to wrap my head around how to call 2 different functions to clear first and then update with a button click event.


回答1:


You can implement the remove function as follows:

function remove() {
  var cellUpdate = cell.selectAll("rect")
  const length = cell.selectAll("rect").data().length

  var cellExit = cellUpdate.transition()
    .delay(function(d, i) { return (length - i) * 7; })
    .duration(updateDuration)
    .attr("width", 0)
    .remove();
}

cellUpdate is the selection of the cells that you want to remove. The length can be retrieved from the number of data elements or the number of nodes in the group (for the example data() was used). After the selection is retrieved you can apply the desired transition with delayed duration on it width, opacity etc.

Here is a sample block that allows you to achieve the desired goal: https://blockbuilder.org/cstefanache/e3110f130394eb71b9adfb5060ef2b78



来源:https://stackoverflow.com/questions/55376374/clearing-and-updating-svg-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!