canvas动态画圆,示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>动态画圆</title>
<style type="text/css">
body {
padding: 100px 100px;
}
canvas {
background: lightgreen;
margin-top: 20px;
display: block;
}
</style>
</head>
<body>
<input type="text" placeholder="请输入百分比">
<input type="button" value="点击绘制">
<canvas id="canvas" width=500px height=500px></canvas>
<script type="text/javascript">
// 取元素
var canvas = document.getElementById('canvas');
var text = document.getElementsByTagName('input')[0];
var btn = document.getElementsByTagName('input')[1];
// 绘制图形
var radius = 100; // 圆的半径
var context = canvas.getContext('2d');
// context.arc() 绘制图形
// 圆心坐标X Y、radius、start、end、false=顺时针
function draw(end) {
context.beginPath();
context.moveTo(canvas.width/2, canvas.height/2);
context.arc(canvas.width/2, canvas.height/2, radius, 0, end, false);
context.closePath();
context.fillStyle = 'red';
context.fill();
}
// draw(2*Math.PI);
// 百分比 -- Math.PI
function change(value) {
var num = value.substring(0, value.length-1);
return Math.PI*2*num/100;
}
// 验证用户输入信息
function inputErr(value) {
var textReg = RegExp(/^(100|[1-9]?\d(\.\d\d?)?)%$/);
var result = textReg.test(value);
return result;
}
// 按钮事件
btn.onclick = function() {
if (!inputErr(text.value)) {
alert('请输入百分比');
return;
}
// 利用定时器实现动态效果
var numberEnd = 0;
var timer = setInterval(function() {
numberEnd ++;
draw(numberEnd/100*2*Math.PI);
if (numberEnd >= parseInt(text.value)) {
draw(change(text.value));
clearInterval(timer);
}
}, 10)
}
</script>
</body>
</html>
网友评论