简介
本文分享两种实现爱心动态效果的方法:一种是基于 Python 的粒子动画,另一种是基于 HTML5 Canvas 的文字飘动效果。
Python 爱心粒子动画
该方案使用 Python 生成动态的爱心形状,通过数学公式计算坐标并模拟扩散效果。以下是完整的可运行代码示例,包含必要的辅助函数定义。
import random
from math import sin, cos, pi
class HeartAnimation:
def __init__(self, generate_frame=20):
# 原始爱心坐标集合
self._points = set()
# 边缘扩散效果点坐标集合
self._edge_diffusion_points = set()
# 中心扩散效果点坐标集合
self._center_diffusion_points = set()
# 每帧动态点坐标
self.all_points = {}
self.build(2000)
self.random_halo = 1000
self.generate_frame = generate_frame
for frame in range(generate_frame):
self.calc(frame)
def build(self, number):
for _ in range(number):
t = random.uniform(0, 2 * pi)
x, y = heart(t)
self._points.add((x, y))
# 爱心内扩散
for _x, _y in (._points):
_ ():
x, y = scatter_inside(_x, _y, )
._edge_diffusion_points.add((x, y))
point_list = (._points)
_ ():
x, y = random.choice(point_list)
x, y = scatter_inside(x, y, )
._center_diffusion_points.add((x, y))
():
X, Y
force = / (((x - X) ** + (y - Y) ** ) ** )
dx = ratio * force * (x - X) + random.randint(-, )
dy = ratio * force * (y - Y) + random.randint(-, )
x - dx, y - dy
():
ratio = * curve(generate_frame / * pi)
halo_radius = ( + * ( + curve(generate_frame / * pi)))
halo_number = (
+ * (curve(generate_frame / * pi) ** ))
all_points = []
heart_halo_point = ()
_ (halo_number):
t = random.uniform(, * pi)
x, y = heart(t, shrink_ratio=)
x, y = shrink(x, y, halo_radius)
(x, y) heart_halo_point:
heart_halo_point.add((x, y))
x += random.randint(-, )
y += random.randint(-, )
size = random.choice((, , ))
all_points.append((x, y, size))
x, y ._points:
x, y = .calc_position(x, y, ratio)
size = random.randint(, )
all_points.append((x, y, size))
x, y ._edge_diffusion_points:
x, y = .calc_position(x, y, ratio)
size = random.randint(, )
all_points.append((x, y, size))
.all_points[generate_frame] = all_points
x, y ._center_diffusion_points:
x, y = .calc_position(x, y, ratio)
size = random.randint(, )
all_points.append((x, y, size))
.all_points[generate_frame] = all_points
X, Y = ,
():
x = * sin(t) **
y = * cos(t) - * cos( * t) - * cos( * t) - cos( * t)
x * shrink_ratio, y * shrink_ratio
():
r = - (((x) + (y)) / )**
x * r, y * r
():
sin(t) * cos(t)
():
x * (radius / ), y * (radius / )


