简体   繁体   中英

Using a range slider to change the radius of an SVG circle

So basically this script uses the output from a range slider to change the radius of an SVG circle. There are two circles however only one of the circles changes in size when the slider is adjusted.

var slider = document.getElementById("myRange");
var output = document.getElementById("circle_radius");
output.innerHTML = slider.value;
slider.oninput = function() {
  output.innerHTML = this.value;
  update(this.value)
}
var c1 = d3.select("circle")
var c2 = d3.select("circle1")

function update(update_radius) {
  c1.transition()
    .ease(d3.easeLinear)
    .duration(2000)
    .delay(100)
    .attr("r", update_radius)
  c2.transition()
    .ease(d3.easeLinear)
    .duration(2000)
    .attr("r",update_radius)
}

Your issue is with d3.select . You're attempting to select an element like <circle1> rather than an id or class.

You should add id attributes to your circles and select them by id instead.

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <circle id="circle1" cx="50" cy="50" r="50"/>
</svg>
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <circle id="circle2" cx="50" cy="50" r="50"/>
</svg>

Then you can do

var c1 = d3.select("#circle1")
var c2 = d3.select("#circle2")

Since you're doing a delay only for the second circle, here's a more general solution. Group the relevant circles with a class:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <circle class="slider-circle" cx="50" cy="50" r="50"/>
  <circle class="slider-circle" cx="50" cy="50" r="50"/>
</svg>

Then, using a selection with all the circles, transition them with a delay based on the index:

var circles = d3.selectAll(".slider-circle")
function update(update_radius) {
  circles.transition()
    .ease(d3.easeLinear)
    .duration(2000)
    .delay((d, i) => i * 100) // i = 0, delay = 0; i = 1, delay = 100
    .attr("r", update_radius)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM