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
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); | |
} |