HTML5愛(ài)心飄落代碼是一種常見(jiàn)的網(wǎng)頁(yè)動(dòng)畫(huà)效果,可以讓網(wǎng)頁(yè)增加一些浪漫與溫馨的氛圍。下面是一段HTML5愛(ài)心飄落代碼:
<!DOCTYPE html> <html> <head> <title>HTML5愛(ài)心飄落效果</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <canvas id="heart"></canvas> <script> var hearts = []; var heartImage = new Image(); heartImage.src = 'heart.png'; function getCursorPosition(e) { var x; var y; if (e.pageX || e.pageY) { x = e.pageX; y = e.pageY; } else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } x -= canvas.offsetLeft; y -= canvas.offsetTop; var heart = new Heart(x, y); hearts.push(heart); } function Heart(x, y) { this.x = x || Math.random() * canvas.width; this.y = y || Math.random() * canvas.height; this.size = Math.random() * 20 + 10; this.image = heartImage; } Heart.prototype.draw = function() { ctx.drawImage(this.image, this.x, this.y, this.size, this.size); } function animate() { requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); for (var i = 0; i< hearts.length; i++) { hearts[i].y += Math.random() * 5 + 1; hearts[i].x += Math.random() * 2 - 1; hearts[i].size -= 0.05; if (hearts[i].size< 0) { hearts.splice(i, 1); i--; } else { hearts[i].draw(); } } } var canvas = document.getElementById('heart'); var ctx = canvas.getContext('2d'); canvas.addEventListener('mousemove', getCursorPosition); animate(); </script> </body> </html>
上述代碼中,包含了一段HTML5的畫(huà)布代碼和JavaScript腳本代碼,通過(guò)canvas元素和JavaScript腳本控制愛(ài)心的運(yùn)動(dòng)軌跡。該效果實(shí)現(xiàn)了鼠標(biāo)在畫(huà)布區(qū)域移動(dòng)時(shí),在畫(huà)布上不停地生成、飄落和消失的愛(ài)心圖案,從而營(yíng)造了浪漫和溫馨的氛圍。