Skip to content

Instantly share code, notes, and snippets.

@Fil
Created March 23, 2019 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fil/ed6b4881e552006446e6c3533d3b84b9 to your computer and use it in GitHub Desktop.
Save Fil/ed6b4881e552006446e6c3533d3b84b9 to your computer and use it in GitHub Desktop.
Round slider (d3v5)
license: mit

Normally, HTML provides traditional sliders with linear shape such as the Input Range Object. This example shows how to create a round slider using D3.js.

forked from fabiovalse's block: Round slider

.circumference {
fill: #fff;
stroke: #f2f2f2;
stroke-width: 5px;
}
.dot circle:hover {
cursor: pointer;
}
.dot circle {
fill: lightsteelblue;
stroke: steelblue;
stroke-width: 1.5px;
}
.dot circle.dragging {
fill: red;
stroke: brown;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3.js Round Slider</title>
<link rel="stylesheet" href="index.css">
<script src="http://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
var width = 960,
height = 500;
var circumference_r = 100;
var drag = d3.drag()
.subject(function(d) { return d; })
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
var container = svg.append("g");
var circumference = container.append('circle')
.attr('r', circumference_r)
.attr('class', 'circumference');
handle = [{
x: 0,
y: -circumference_r
}];
handle_circle = container.append("g")
.attr("class", "dot")
.selectAll('circle')
.data(handle)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return d.x;})
.attr("cy", function(d) { return d.y;})
.call(drag);
function dragstarted(d) {
d3.event.sourceEvent.stopPropagation();
d3.select(this)
.classed("dragging", true);
}
function dragged(d) {
d_from_origin = Math.sqrt(Math.pow(d3.event.x,2)+Math.pow(d3.event.y,2));
alpha = Math.acos(d3.event.x/d_from_origin);
d3.select(this)
.attr("cx", d.x = circumference_r*Math.cos(alpha))
.attr("cy", d.y = d3.event.y < 0 ? -circumference_r*Math.sin(alpha) : circumference_r*Math.sin(alpha));
}
function dragended(d) {
d3.select(this)
.classed("dragging", false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment