Skip to content

Instantly share code, notes, and snippets.

@fabiovalse
Last active August 29, 2015 14:28
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 fabiovalse/cd03939330a24f0fbd12 to your computer and use it in GitHub Desktop.
Save fabiovalse/cd03939330a24f0fbd12 to your computer and use it in GitHub Desktop.
Round slider

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.

.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.v3.min.js"></script>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
var width = 960,
height = 500;
var circumference_r = 100;
var drag = d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", dragstarted)
.on("drag", dragged)
.on("dragend", 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