帮我写一个js爱心代码爱心太普通了
以下是一个比较特别的js爱心代码,它会随机生成不同颜色和大小的爱心,并且会以不同的速度和方向漂浮:
<!DOCTYPE html>
<html>
<head>
<title>JS爱心代码</title>
<style>
body {
background-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<script>
// 定义爱心类
function Heart() {
// 随机生成爱心的颜色和大小
this.color = '#' + Math.floor(Math.random() * 16777215).toString(16);
this.size = Math.floor(Math.random() * 30) + 10;
// 创建爱心元素
this.element = document.createElement('div');
this.element.style.position = 'absolute';
this.element.style.width = this.size + 'px';
this.element.style.height = this.size + 'px';
this.element.style.background = 'radial-gradient(circle at 50% 0%, ' + this.color + ', transparent 70%)';
this.element.style.transform = 'rotate(45deg)';
// 随机生成爱心的初始位置和速度
this.x = Math.floor(Math.random() * window.innerWidth);
this.y = Math.floor(Math.random() * window.innerHeight);
this.speed = Math.floor(Math.random() * 5) + 1;
this.angle = Math.floor(Math.random() * 360);
// 将爱心元素添加到页面中
document.body.appendChild(this.element);
// 定时器,更新爱心的位置和角度
this.timer = setInterval(function() {
var radians = this.angle * Math.PI / 180;
var dx = this.speed * Math.cos(radians);
var dy = this.speed * Math.sin(radians);
this.x += dx;
this.y += dy;
this.angle += 5;
if (this.x < -this.size || this.x > window.innerWidth ||
this.y < -this.size || this.y > window.innerHeight) {
// 爱心超出页面范围,移除元素和定时器
clearInterval(this.timer);
document.body.removeChild(this.element);
} else {
// 更新爱心的位置
this.element.style.left = this.x + 'px';
this.element.style.top = this.y + 'px';
}
}.bind(this), 20);
}
// 定时器,每隔一定时间生成一个新的爱心
setInterval(function() {
new Heart();
}, 500);
</script>
</body>
</html>
你可以将上面的代码复制到一个HTML文件中并打开,就可以看到漂浮的爱心了。如果需要调整爱心的大小、速度、数量等参数,可以修改代码中相应的值
原文地址: https://www.cveoy.top/t/topic/c0xF 著作权归作者所有。请勿转载和采集!