写一个动态跳动爱心代码
时间: 2023-11-03 14:59:28 浏览: 167
用web写一个跳动的爱心-源代码
以下是一个使用 HTML、CSS 和 JavaScript 编写的动态跳动爱心代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态跳动爱心</title>
<style>
body {
background: #000;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
var hearts = [];
var heartImage = new Image();
heartImage.src = 'https://i.imgur.com/9v1nQaF.png';
function Heart() {
this.x = Math.random() * width;
this.y = Math.random() * height;
this.size = Math.random() * 0.3 + 0.1;
this.speed = Math.random() * 1.5 + 0.5;
this.angle = Math.random() * Math.PI * 2;
this.rotationSpeed = Math.random() * Math.PI * 0.04 - Math.PI * 0.02;
}
Heart.prototype.update = function() {
this.x += Math.sin(this.angle) * this.speed;
this.y += Math.cos(this.angle) * this.speed;
this.angle += this.rotationSpeed;
if (this.x < -this.size * 10 || this.x > width + this.size * 10 || this.y < -this.size * 10 || this.y > height + this.size * 10) {
this.x = Math.random() * width;
this.y = -this.size * 10;
}
}
Heart.prototype.draw = function() {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.scale(this.size, this.size);
ctx.drawImage(heartImage, -20, -20, 40, 40);
ctx.restore();
}
function createHearts(num) {
for (var i = 0; i < num; i++) {
hearts.push(new Heart());
}
}
createHearts(50);
function loop() {
ctx.clearRect(0, 0, width, height);
for (var i = 0; i < hearts.length; i++) {
hearts[i].update();
hearts[i].draw();
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>
```
你可以将上述代码复制粘贴到一个 HTML 文件中并保存,在浏览器中打开该文件即可看到动态跳动爱心效果。
阅读全文