js实现转圈
实现圆形旋转动画
使用CSS和JavaScript结合实现一个简单的旋转圆圈动画。通过CSS定义动画样式,JavaScript控制动画的触发或停止。
HTML结构
<div class="spinner"></div>
<button id="toggleButton">Toggle Animation</button>
CSS样式
.spinner {
width: 50px;
height: 50px;
border: 5px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top-color: #3498db;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
JavaScript控制
const spinner = document.querySelector('.spinner');
const toggleButton = document.getElementById('toggleButton');
toggleButton.addEventListener('click', () => {
const isPaused = spinner.style.animationPlayState === 'paused';
spinner.style.animationPlayState = isPaused ? 'running' : 'paused';
});
纯JavaScript实现旋转
通过requestAnimationFrame动态更新旋转角度,实现更灵活的控制。
HTML结构
<canvas id="spinnerCanvas" width="100" height="100"></canvas>
<button id="startButton">Start</button>
<button id="stopButton">Stop</button>
JavaScript代码
const canvas = document.getElementById('spinnerCanvas');
const ctx = canvas.getContext('2d');
let angle = 0;
let animationId = null;
function drawSpinner() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(50, 50, 40, 0, Math.PI * 2);
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 8;
ctx.stroke();
ctx.beginPath();
ctx.arc(50, 50, 40, angle, angle + Math.PI/2);
ctx.strokeStyle = '#3498db';
ctx.lineWidth = 8;
ctx.stroke();
angle += 0.1;
if (angle > Math.PI * 2) angle = 0;
animationId = requestAnimationFrame(drawSpinner);
}
document.getElementById('startButton').addEventListener('click', () => {
if (!animationId) {
drawSpinner();
}
});
document.getElementById('stopButton').addEventListener('click', () => {
cancelAnimationFrame(animationId);
animationId = null;
});
SVG实现旋转动画
利用SVG的transform属性实现平滑旋转效果。
HTML结构

<svg width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" stroke="#ddd" stroke-width="8" fill="none"/>
<circle cx="50" cy="10" r="8" fill="#3498db" id="rotatingDot">
<animateTransform
attributeName="transform"
type="rotate"
from="0 50 50"
to="360 50 50"
dur="1s"
repeatCount="indefinite"/>
</circle>
</svg>






