js实现转圈
使用 CSS 和 JavaScript 实现旋转动画
通过 CSS animation 和 @keyframes 实现旋转效果,JavaScript 用于控制动画的启停。
HTML 结构
<div id="spinner"></div>
<button id="toggle">Toggle Spin</button>
CSS 样式
#spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
JavaScript 控制
const spinner = document.getElementById('spinner');
const toggleBtn = document.getElementById('toggle');
toggleBtn.addEventListener('click', () => {
const isSpinning = spinner.style.animationPlayState !== 'paused';
spinner.style.animationPlayState = isSpinning ? 'paused' : 'running';
});
纯 JavaScript 实现旋转(Canvas)
使用 requestAnimationFrame 逐帧绘制旋转效果,适合需要动态控制的场景。
HTML 结构
<canvas id="spinnerCanvas" width="100" height="100"></canvas>
<button id="startBtn">Start</button>
<button id="stopBtn">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.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate((angle * Math.PI) / 180);
ctx.fillStyle = '#3498db';
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(30, 0);
ctx.lineTo(15, 30);
ctx.closePath();
ctx.fill();
ctx.restore();
angle = (angle + 2) % 360;
animationId = requestAnimationFrame(drawSpinner);
}
document.getElementById('startBtn').addEventListener('click', () => {
if (!animationId) drawSpinner();
});
document.getElementById('stopBtn').addEventListener('click', () => {
cancelAnimationFrame(animationId);
animationId = null;
});
使用 SVG 实现平滑旋转
SVG 的 transform 属性结合 JavaScript 实现高性能旋转动画。
HTML 结构
<svg id="spinnerSvg" width="100" height="100" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" stroke="#3498db" stroke-width="8" fill="none" stroke-dasharray="60 20" />
</svg>
<button id="svgToggle">Toggle</button>
JavaScript 控制
const svgSpinner = document.getElementById('spinnerSvg');
const svgCircle = svgSpinner.querySelector('circle');
let rotation = 0;
let svgInterval = null;
function startSvgSpin() {
svgInterval = setInterval(() => {
rotation = (rotation + 2) % 360;
svgCircle.setAttribute('transform', `rotate(${rotation} 50 50)`);
}, 16);
}
document.getElementById('svgToggle').addEventListener('click', () => {
if (svgInterval) {
clearInterval(svgInterval);
svgInterval = null;
} else {
startSvgSpin();
}
});
注意事项
- 性能优化:CSS 动画性能通常优于 JavaScript 实现的动画。
- 浏览器兼容性:
requestAnimationFrame和 CSSanimation在现代浏览器中支持良好。 - 移动端适配:使用
transform代替top/left变化以避免布局重排。







