跳动粒子爱心代码html
时间: 2023-09-22 22:15:20 浏览: 424
以下是一个简单的跳动粒子爱心代码,可以在 HTML 中使用:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跳动粒子爱心</title>
<style>
body {
background-color: #000;
}
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 particles = [];
var particleCount = 100;
var heart = new Image();
heart.src = "https://freepngimg.com/thumb/heart/2-2-heart-free-download-png.png";
heart.onload = function() {
canvas.width = heart.width;
canvas.height = heart.height;
ctx.drawImage(heart, 0, 0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var i = 0; i < imageData.data.length; i += 4) {
var r = imageData.data[i];
var g = imageData.data[i + 1];
var b = imageData.data[i + 2];
if (r + g + b < 100) {
var x = (i / 4) % canvas.width;
var y = Math.floor((i / 4) / canvas.width);
particles.push({
x: x,
y: y,
size: 2,
color: "red",
speedX: Math.random() * 4 - 2,
speedY: Math.random() * 4 - 2,
directionX: Math.random() * 2 - 1,
directionY: Math.random() * 2 - 1
});
}
}
};
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
var p = particles[i];
p.x += p.speedX * p.directionX;
p.y += p.speedY * p.directionY;
if (p.x < 0 || p.x > canvas.width) {
p.directionX = -p.directionX;
}
if (p.y < 0 || p.y > canvas.height) {
p.directionY = -p.directionY;
}
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>
```
这段代码会在页面中显示一个跳动的粒子爱心效果,并且会随着鼠标移动而移动。你可以将其复制粘贴到一个 HTML 文件中并打开查看效果。
阅读全文