返回
创作属于自己的曲线运动气泡
前端
2024-01-29 23:38:01
创作属于自己的曲线运动气泡
最近在写一个HTML项目,里面需要实现一个效果:当鼠标移动到人物上时,冒出一些做曲线运动的气泡。一开始确实没什么思路,在网上搜集了下资料,能差不多的写出来了,所以写个博客记录下,也希望给有需要的朋友提供一些参考。
准备工作
在开始之前,你需要确保你有以下工具:
- 一个文本编辑器(如记事本或Sublime Text)
- 一个网络浏览器(如Chrome或Firefox)
- 一个图像编辑器(如Photoshop或GIMP)
HTML和CSS
首先,我们需要创建一个HTML文件和一个CSS文件。在HTML文件中,我们需要包含CSS文件,并在body元素中添加一个canvas元素。canvas元素将用作我们的绘图表面。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
canvas {
width: 100%;
height: 100%;
background-color: #000;
}
JavaScript
接下来,我们需要创建一个JavaScript文件。在JavaScript文件中,我们需要定义一个函数来绘制气泡。气泡的运动轨迹是一个抛物线,我们可以使用JavaScript中的Math.sin()和Math.cos()函数来计算气泡的坐标。
function drawBubble(ctx, x, y, radius, color) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
然后,我们需要创建一个函数来控制气泡的运动。气泡的运动速度和加速度都将是常数。
function updateBubble(bubble) {
bubble.x += bubble.vx;
bubble.y += bubble.vy;
bubble.vy += bubble.ay;
}
最后,我们需要创建一个函数来渲染气泡。在渲染函数中,我们需要遍历气泡数组,并对每个气泡调用drawBubble()函数和updateBubble()函数。
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < bubbles.length; i++) {
drawBubble(ctx, bubbles[i].x, bubbles[i].y, bubbles[i].radius, bubbles[i].color);
updateBubble(bubbles[i]);
}
requestAnimationFrame(render);
}
完整项目
完整的项目代码如下:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="script.js"></script>
</body>
</html>
canvas {
width: 100%;
height: 100%;
background-color: #000;
}
function drawBubble(ctx, x, y, radius, color) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = color;
ctx.fill();
}
function updateBubble(bubble) {
bubble.x += bubble.vx;
bubble.y += bubble.vy;
bubble.vy += bubble.ay;
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < bubbles.length; i++) {
drawBubble(ctx, bubbles[i].x, bubbles[i].y, bubbles[i].radius, bubbles[i].color);
updateBubble(bubbles[i]);
}
requestAnimationFrame(render);
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const bubbles = [];
for (let i = 0; i < 100; i++) {
const bubble = {
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
radius: Math.random() * 10,
color: `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`,
vx: Math.random() * 5 - 2.5,
vy: Math.random() * 5 - 2.5,
ay: 0.05
};
bubbles.push(bubble);
}
render();
你可以在https://zdjzpg.github.io/html5/上查看完整的项目。