HTML 5 重力圖片源代碼是一種HTML語言的標簽和屬性組合,它能夠實現圖片的重力和運動效果,可以為網站的視覺效果以及用戶交互性帶來一些新的體驗。
<!DOCTYPE html> <html> <head> <title>HTML 5 重力圖片示例</title> <meta charset="UTF-8"> <style> canvas { border: solid 1px #333; } </style> </head> <body> <canvas id="canvas" width="800" height="600"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; function Particle(x, y, radius) { this.x = x; this.y = y; this.radius = radius; this.color = 'rgb(' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random() * 255) + ',' + Math.floor(Math.random()*255) + ')'; this.vx = Math.random() * 10 - 5; this.vy = Math.random() * 10 - 5; } Particle.prototype.move = function() { this.x += this.vx; this.y += this.vy; }; Particle.prototype.draw = function() { context.beginPath(); context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); context.closePath(); context.fillStyle = this.color; context.fill(); }; Particle.prototype.checkCollision = function() { if (this.x - this.radius < 0) { this.x = this.radius; this.vx *= -1; } if (this.x + this.radius > canvas.width) { this.x = canvas.width - this.radius; this.vx *= -1; } if (this.y - this.radius < 0) { this.y = this.radius; this.vy *= -1; } if (this.y + this.radius > canvas.height) { this.y = canvas.height - this.radius; this.vy *= -1; } }; var particles = []; for (var i = 0; i < 20; i++) { particles.push(new Particle(Math.random() * canvas.width, Math.random() * canvas.height, Math.random() * 20)); } function animate() { context.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i < particles.length; i++) { particles[i].draw(); particles[i].move(); particles[i].checkCollision(); } requestAnimationFrame(animate); } animate(); </script> </body> </html>
上述代碼展示了一個基本的重力圖片運動的動畫,其中包含了一個名為Particle的構造函數,用于創建粒子對象。通過對粒子對象的vx和vy值來控制粒子的運動方向和速度,并在每一幀中進行碰撞檢測,來實現物理效果。此外,還使用了HTML 5中的Canvas標簽和Web Animation API的requestAnimationFrame函數來實現動畫效果。
上一篇設置縱向自動滾動條css
下一篇設置的CSS樣式不顯示