Skip to content

Instantly share code, notes, and snippets.

@alexzhou
Last active December 26, 2015 16:29
Show Gist options
  • Save alexzhou/7179868 to your computer and use it in GitHub Desktop.
Save alexzhou/7179868 to your computer and use it in GitHub Desktop.
make circle progressbar with svg 用svg 画环形进度条
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Ring Progress Bar</title>
</head>
<body>
<section>
<input type="range" value="64" />
<svg>
<path id="ring" fill="#76B13C" />
<circle cx="100" cy="100" r="82" fill="#F7F6F4" />
</svg>
</section>
<script type="text/javascript">
(function (){
var document = window.document,
ring = document.getElementsByTagName('path')[0],
range = document.getElementsByTagName('input')[0],
text = document.getElementsByTagName('text')[0],
Math = window.Math,
toRadians = Math.PI / 180, //每度对应的弧度
r = 100;
function draw() {
var degrees = range.value * 3.5999, //进度对应的角度是多少,value*(360/100)
rad = degrees * toRadians, //角度转换成弧度
//极坐标转换成直角坐标
x = (Math.sin(rad) * r).toFixed(2),
y = -(Math.cos(rad) * r).toFixed(2),
//大于180度时候画大角度弧,小于180度的画小角度弧,(deg > 180) ? 1 : 0
lenghty = window.Number(degrees > 180),
//path 属性
descriptions = ['M', 0, 0, 'v', -r, 'A', r, r, 0/*x轴偏移度*/, lenghty, 1/*顺时针画弧*/, x, y, 'z'/*闭合*/];
// 给path 设置属性
ring.setAttribute('d', descriptions.join(' '));
//修改进度文本
text.textContent = range.value;
}
//修改坐标轴的位置
ring.setAttribute('transform', 'translate(' + r + ', ' + r + ')');
// 绑定事件
range.addEventListener('change', draw);
// 首次运行(初始化运行)
draw();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment