HTML5中的動畫特效可以為網站、游戲、手機應用等用戶界面提供更加豐富和生動的體驗。以下是一些常用的HTML5動畫特效代碼。
1. CSS3 動畫特效
/* 旋轉動畫 */ .rotate { animation: rotate 2s infinite linear; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } /* 左右滑動動畫 */ .slide-left { animation: slide-left 1s ease-in-out infinite alternate; } @keyframes slide-left { from { transform: translateX(0%); } to { transform: translateX(-50%); } }
2. JavaScript 動畫特效
/* 淡入淡出動畫 */ function fadeIn(element) { var op = 0.1; // initial opacity element.style.display = 'block'; var timer = setInterval(function () { if (op >= 1){ clearInterval(timer); } element.style.opacity = op; element.style.filter = 'alpha(opacity=' + op * 100 + ")"; op += op * 0.1; }, 10); } function fadeOut(element) { var op = 1; // initial opacity var timer = setInterval(function () { if (op<= 0.1){ clearInterval(timer); element.style.display = 'none'; } element.style.opacity = op; element.style.filter = 'alpha(opacity=' + op * 100 + ")"; op -= op * 0.1; }, 10); } /* 緩動動畫 */ function animate(element, target, duration) { var startTime = new Date().getTime(); var startValue = parseInt(element.style.left) || 0; var distance = target - startValue; function step() { var now = new Date().getTime(); var timeElapsed = now - startTime; var progress = timeElapsed / duration; var value = startValue + (distance * progress); element.style.left = value + 'px'; if (progress< 1) { requestAnimationFrame(step); } } requestAnimationFrame(step); }
3. Canvas 動畫特效
/* 爆炸效果 */ function explode(x, y, size) { var particles = []; for (var i = 0; i< 20; i++) { particles.push({ x: x, y: y, size: size, speedX: (Math.random() - 0.5) * 5, speedY: (Math.random() - 0.5) * 5, color: '#'+Math.floor(Math.random()*16777215).toString(16) }); } function drawParticle(particle) { context.fillStyle = particle.color; context.beginPath(); context.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2); context.closePath(); context.fill(); } function update() { context.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(function (particle) { particle.x += particle.speedX; particle.y += particle.speedY; drawParticle(particle); }); requestAnimationFrame(update); } update(); } /* 閃電效果 */ function lightning() { context.clearRect(0, 0, canvas.width, canvas.height); context.beginPath(); context.moveTo(0, Math.random() * canvas.height); context.lineTo(canvas.width, Math.random() * canvas.height); context.strokeStyle = '#FFFFFF'; context.lineWidth = 5; context.stroke(); setTimeout(lightning, 500); }這些動畫特效只是冰山一角,HTML5中還有很多強大的動畫庫和插件可供使用,可以根據需求選擇合適的方案來實現更加出色的動畫效果。