示例-旋转-spinner改进:从暂停的地方开始
最下面调用draw()的时候,(!startTime)会运行2次。
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <title>My test page</title> <style> html { background-color: white; height: 100%; } body { height: inherit; background-color: red; margin: 0; display: flex; justify-content: center; align-items: center; } div { display: inline-block; font-size: 10rem; } </style> </head> <body> <div>↻</div> <script> const spinner = document.querySelector('div'); let rotateCount = 0; let tmpRotateCount = 0; let startTime = null; let rAF; let spinning = true; function draw(timestamp) { if (!startTime){// && !!timestamp) { startTime = timestamp; console.log('----------') console.log('timestamp: '+ timestamp); console.log('startTime: '+ startTime); console.log('rotateCount: ' + tmpRotateCount); if (tmpRotateCount > 0){ startTime = startTime - tmpRotateCount * 10 console.log('new startTime: ' + startTime); } console.log('end----------') } //console.log(timestamp); //timestamp不停的在增加,不是调用draw()的时间。 rotateCount = (timestamp - startTime) / 10; rotateCount %= 360; spinner.style.transform = `rotate(${rotateCount}deg)`; rAF = requestAnimationFrame(draw); } draw(); //window.addEventListener('click', function() { document.body.addEventListener('click', function() { if (spinning) { cancelAnimationFrame(rAF); spinning = false; startTime = null; } else { startTime = null; tmpRotateCount = rotateCount; draw(); spinning = true; } }); </script> </body> </html>
阅读量: 530
发布于:
修改于:
发布于:
修改于: