实现圆上有个小点可以一直动态移动的效果
requestAnimationFrame()方法实现
window.requestAnimationFrame()方法告诉浏览器您希望执行动画,并请求浏览器调用指定的函数以在下次重绘之前更新动画。该方法将回调作为在重绘之前调用的参数。
window.requestAnimationFrame(callback);
**参数callback:**指定在更新动画以进行下一次重绘时要调用的函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas width=500 height=500 class="cavans"></canvas>
<script>
const cvs = document.querySelector('.cavans')
const cxt = cvs.getContext('2d')
let angle = 30
function render() {
cxt.clearRect(0, 0, 500, 500) //每次循环开始需要清除矩形的轨迹
cxt.arc(100, 100, 50, 0, 2 * Math.PI)
cxt.fillStyle = 'pink'
cxt.fill() //绘制一个圆
//绘制圆上的方块
angle += 1
cxt.beginPath()
const x = 100 + 50 * Math.cos(angle * Math.PI / 180)
const y = 100 + 50 * Math.sin(angle * Math.PI / 180)
cxt.fillStyle = 'red'
cxt.fillRect(x, y, 4, 4)
window.requestAnimationFrame(render)
}
render()
</script>
</body>
</html>
定时器实现
setInterval() 每隔多长时间自动执行方法,时间是以豪秒为单位的(1000ms=1s)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas width=500 height=500 class="cavans"></canvas>
<script>
const cvs = document.querySelector('.cavans')
const cxt = cvs.getContext('2d')
let angle = 30
function render() {
cxt.clearRect(0, 0, 500, 500) //每次循环开始需要清除矩形的轨迹
cxt.arc(100, 100, 50, 0, 2 * Math.PI)
cxt.fillStyle = 'pink'
cxt.fill() //绘制一个圆
//绘制圆上的方块
angle += 1
cxt.beginPath()
const x = 100 + 50 * Math.cos(angle * Math.PI / 180)
const y = 100 + 50 * Math.sin(angle * Math.PI / 180)
cxt.fillStyle = 'red'
cxt.fillRect(x, y, 4, 4)
}
用计时器实现动态
setInterval(function() {
render()
}, 1000 / 60)
</script>
</body>
</html>