爱心代码李峋同款爱心 python html

目录

前言

一、python

1.python 第一个

2.python第二个

二、HTML

1.第一个

2.第二个html

3.第三个html

3.第四个html

总结


前言

最近那个电视剧很火,就是搞爱心代码的,本人兴趣使然,在网上搜集了一些代码,经过一定修改,做一个小总结。源文件直接免费下载点此处

一、python

运行

主要用的包都是那么几个,csdn搜pycharm怎么导包就可以。

1.python 第一个

成品效果

 

调整思路

HEART_COLOR = "#EEAEEE"  #引号内修改颜色!颜色代码放在文章末尾

双引号里面可以在csdn搜RGB颜色,比如这个兄弟的,直接看里面的对照表,把包括#的数字或字母替换就可以换颜色了

代码如下

import random
from math import sin, cos, pi, log
from tkinter import *

CANVAS_WIDTH = 840  # 画布的宽
CANVAS_HEIGHT = 680  # 画布的高
CANVAS_CENTER_X = CANVAS_WIDTH / 2  # 画布中心的X轴坐标
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2  # 画布中心的Y轴坐标
IMAGE_ENLARGE = 11  # 放大比例

HEART_COLOR = "#EEAEEE"  #引号内修改颜色!颜色代码放在文章末尾

def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
    """
    “爱心函数生成器”
    :param shrink_ratio: 放大比例
    :param t: 参数
    :return: 坐标
    """
    # 基础函数
    x = 17 * (sin(t) ** 3)
    y = -(16 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(3 * t))

    # 放大
    #x *= shrink_ratio
    #y *= shrink_ratio
    x*=IMAGE_ENLARGE
    y*=IMAGE_ENLARGE
    # 移到画布中央
    x += CANVAS_CENTER_X
    y += CANVAS_CENTER_Y

    return int(x), int(y)


def scatter_inside(x, y, beta=0.15):
    """
    随机内部扩散
    :param x: 原x
    :param y: 原y
    :param beta: 强度
    :return: 新坐标
    """
    ratio_x = - beta * log(random.random())
    ratio_y = - beta * log(random.random())

    dx = ratio_x * (x - CANVAS_CENTER_X)
    dy = ratio_y * (y - CANVAS_CENTER_Y)

    return x - dx, y - dy


def shrink(x, y, ratio):
    """
    抖动
    :param x: 原x
    :param y: 原y
    :param ratio: 比例
    :return: 新坐标
    """
    force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6)  # 这个参数...
    dx = ratio * force * (x - CANVAS_CENTER_X)
    dy = ratio * force * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def curve(p):
    """
    自定义曲线函数,调整跳动周期
    :param p: 参数
    :return: 正弦
    """
    # 可以尝试换其他的动态函数,达到更有力量的效果(贝塞尔?)
    return 2 * (2 * sin(4 * p)) / (2 * pi)


class Heart:
    """
    爱心类
    """

    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_function(t)
            self._points.add((x, y))

        # 爱心内扩散
        for _x, _y in list(self._points):
            for _ in range(3):
                x, y = scatter_inside(_x, _y, 0.05)
                self._edge_diffusion_points.add((x, y))

        # 爱心内再次扩散
        point_list = list(self._points)
        for _ in range(10000):
            x, y = random.choice(point_list)
            x, y = scatter_inside(x, y, 0.27)
            self._center_diffusion_points.add((x, y))

    @staticmethod
    def calc_position(x, y, ratio):
        # 调整缩放比例
        force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.420)  # 魔法参数

        dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
        dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)

        return x - dx, y - dy

    def calc(self, generate_frame):
        ratio = 15 * curve(generate_frame / 10 * pi)  # 圆滑的周期的缩放比例

        halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
        halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))

        all_points = []

        # 光环
        heart_halo_point = set()  # 光环的点坐标集合
        for _ in range(halo_number):
            t = random.uniform(0, 2 * pi)  # 随机不到的地方造成爱心有缺口
            x, y = heart_function(t, shrink_ratio=-15)  # 魔法参数
            x, y = shrink(x, y, halo_radius)
            if (x, y) not in heart_halo_point:
                # 处理新的点
                heart_halo_point.add((x, y))
                x += random.randint(-60, 60)
                y += random.randint(-60, 60)
                size = random.choice((1, 1, 2))
                all_points.append((x, y, size))
                all_points.append((x+20, y+20, size))
                all_points.append((x-20, y -20, size))
                all_points.append((x+20, y - 20, size))
                all_points.append((x - 20, y +20, size))

        # 轮廓
        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 3)
            all_points.append((x, y, size))

        # 内容
        for x, y in self._edge_diffusion_points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            all_points.append((x, y, size))

        for x, y in self._center_diffusion_points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            all_points.append((x, y, size))

        self.all_points[generate_frame] = all_points

    def render(self, render_canvas, render_frame):
        for x, y, size in self.all_points[render_frame % self.generate_frame]:
            render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)


def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
    render_canvas.delete('all')
    render_heart.render(render_canvas, render_frame)
    main.after(1, draw, main, render_canvas, render_heart, render_frame + 1)


if __name__ == '__main__':
    root = Tk()
    canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
    canvas.pack()
    heart = Heart()
    draw(root, canvas, heart)
    root.mainloop()

2.python第二个

成品效果

 

调整思路

HEART_COLOR = "#EEAEEE"  #心的颜色

调整颜色的思路同上

代码如下

import random
from math import sin, cos, pi, log
from tkinter import *

CANVAS_WIDTH = 640  # 画布的宽
CANVAS_HEIGHT = 480  # 画布的高
CANVAS_CENTER_X = CANVAS_WIDTH / 2  # 画布中心的X轴坐标
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2  # 画布中心的Y轴坐标
IMAGE_ENLARGE = 11  # 放大比例
HEART_COLOR = "pink"  # 心的颜色


def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
    """
    “爱心函数生成器”
    :param shrink_ratio: 放大比例
    :param t: 参数
    :return: 坐标
    """
    # 基础函数
    x = 16 * (sin(t) ** 3)
    y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))

    # 放大
    x *= shrink_ratio
    y *= shrink_ratio

    # 移到画布中央
    x += CANVAS_CENTER_X
    y += CANVAS_CENTER_Y

    return int(x), int(y)


def scatter_inside(x, y, beta=0.15):
    """
    随机内部扩散
    :param x: 原x
    :param y: 原y
    :param beta: 强度
    :return: 新坐标
    """
    ratio_x = - beta * log(random.random())
    ratio_y = - beta * log(random.random())

    dx = ratio_x * (x - CANVAS_CENTER_X)
    dy = ratio_y * (y - CANVAS_CENTER_Y)

    return x - dx, y - dy


def shrink(x, y, ratio):
    """
    抖动
    :param x: 原x
    :param y: 原y
    :param ratio: 比例
    :return: 新坐标
    """
    force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6)  # 这个参数...
    dx = ratio * force * (x - CANVAS_CENTER_X)
    dy = ratio * force * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def curve(p):
    """
    自定义曲线函数,调整跳动周期
    :param p: 参数
    :return: 正弦
    """
    return 4 * (2 * sin(4 * p)) / (2 * pi)


class Heart:
    """
    爱心类
    """

    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_function(t)
            self._points.add((x, y))

        # 爱心内扩散
        for _x, _y in list(self._points):
            for _ in range(3):
                x, y = scatter_inside(_x, _y, 0.05)
                self._edge_diffusion_points.add((x, y))

        # 爱心内再次扩散
        point_list = list(self._points)
        for _ in range(4000):
            x, y = random.choice(point_list)
            x, y = scatter_inside(x, y, 0.17)
            self._center_diffusion_points.add((x, y))

    @staticmethod
    def calc_position(x, y, ratio):
        # 调整缩放比例
        force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520)

        dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
        dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)

        return x - dx, y - dy

    def calc(self, generate_frame):
        ratio = 10 * curve(generate_frame / 10 * pi)  # 圆滑的周期的缩放比例

        halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
        halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))

        all_points = []

        # 光环
        heart_halo_point = set()  # 光环的点坐标集合
        for _ in range(halo_number):
            t = random.uniform(0, 2 * pi)  # 随机不到的地方造成爱心有缺口
            x, y = heart_function(t, shrink_ratio=11)
            x, y = shrink(x, y, halo_radius)
            if (x, y) not in heart_halo_point:
                # 处理新的点
                heart_halo_point.add((x, y))
                x += random.randint(-11, 11)
                y += random.randint(-11, 11)
                size = random.choice((1, 2, 2))#控制外围粒子的大小
                all_points.append((x, y, size))

        # 轮廓
        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 3)
            all_points.append((x, y, size))

        # 内容
        for x, y in self._center_diffusion_points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            all_points.append((x, y, size))

        self.all_points[generate_frame] = all_points

    def render(self, render_canvas, render_frame):
        for x, y, size in self.all_points[render_frame % self.generate_frame]:
            render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)


def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
    render_canvas.delete('all')
    render_heart.render(render_canvas, render_frame)
    main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)


if __name__ == '__main__':
    root = Tk()  # 一个Tk
    canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
    canvas.pack()
    heart = Heart()  # 心
    draw(root, canvas, heart)  # 开始画画~
    root.mainloop()

二、HTML

html的个人感觉更好,因为有浏览器就支持运行,py的后期得导出成exe才可以在没有环境设备运行,html手机电脑都可以的。

1.第一个

输出样例

调整

<title>canvas爱心</title>   这个canvas爱心字样随便调整可以自己编辑TA的名字之类的

代码如下

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>canvas爱心</title>

<style>
html, body {
  height: 100%;
  padding: 0;
  margin: 0;
  background: #000;
}
canvas {
  position: absolute;
  width: 100%;
  height: 100%;
}</style>
</head>
<body>

<canvas id="pinkboard"></canvas>

<script>
/*
 * Settings
 */
var settings = {
  particles: {
    length:   500, // maximum amount of particles
    duration:   2, // particle duration in sec
    velocity: 100, // particle velocity in pixels/sec
    effect: -0.75, // play with this for a nice effect
    size:      30, // particle size in pixels
  },
};

/*
 * RequestAnimationFrame polyfill by Erik M?ller
 */
(function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());

/*
 * Point class
 */
var Point = (function() {
  function Point(x, y) {
    this.x = (typeof x !== 'undefined') ? x : 0;
    this.y = (typeof y !== 'undefined') ? y : 0;
  }
  Point.prototype.clone = function() {
    return new Point(this.x, this.y);
  };
  Point.prototype.length = function(length) {
    if (typeof length == 'undefined')
      return Math.sqrt(this.x * this.x + this.y * this.y);
    this.normalize();
    this.x *= length;
    this.y *= length;
    return this;
  };
  Point.prototype.normalize = function() {
    var length = this.length();
    this.x /= length;
    this.y /= length;
    return this;
  };
  return Point;
})();

/*
 * Particle class
 */

var Particle = (function() {
  function Particle() {
    this.position = new Point();
    this.velocity = new Point();
    this.acceleration = new Point();
    this.age = 0;
  }
  Particle.prototype.initialize = function(x, y, dx, dy) {
    this.position.x = x;
    this.position.y = y;
    this.velocity.x = dx;
    this.velocity.y = dy;
    this.acceleration.x = dx * settings.particles.effect;
    this.acceleration.y = dy * settings.particles.effect;
    this.age = 0;
  };
  Particle.prototype.update = function(deltaTime) {
    this.position.x += this.velocity.x * deltaTime;
    this.position.y += this.velocity.y * deltaTime;
    this.velocity.x += this.acceleration.x * deltaTime;
    this.velocity.y += this.acceleration.y * deltaTime;
    this.age += deltaTime;
  };
  Particle.prototype.draw = function(context, image) {
    function ease(t) {
      return (--t) * t * t + 1;
    }
    var size = image.width * ease(this.age / settings.particles.duration);
    context.globalAlpha = 1 - this.age / settings.particles.duration;
    context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
  };
  return Particle;
})();

/*
 * ParticlePool class
 */
var ParticlePool = (function() {
  var particles,
      firstActive = 0,
      firstFree   = 0,
      duration    = settings.particles.duration;
  
  function ParticlePool(length) {
    // create and populate particle pool
    particles = new Array(length);
    for (var i = 0; i < particles.length; i++)
      particles[i] = new Particle();
  }
  ParticlePool.prototype.add = function(x, y, dx, dy) {
    particles[firstFree].initialize(x, y, dx, dy);
    
    // handle circular queue
    firstFree++;
    if (firstFree   == particles.length) firstFree   = 0;
    if (firstActive == firstFree       ) firstActive++;
    if (firstActive == particles.length) firstActive = 0;
  };
  ParticlePool.prototype.update = function(deltaTime) {
    var i;
    
    // update active particles
    if (firstActive < firstFree) {
      for (i = firstActive; i < firstFree; i++)
        particles[i].update(deltaTime);
    }
    if (firstFree < firstActive) {
      for (i = firstActive; i < particles.length; i++)
        particles[i].update(deltaTime);
      for (i = 0; i < firstFree; i++)
        particles[i].update(deltaTime);
    }
    
    // remove inactive particles
    while (particles[firstActive].age >= duration && firstActive != firstFree) {
      firstActive++;
      if (firstActive == particles.length) firstActive = 0;
    }
    
    
  };
  ParticlePool.prototype.draw = function(context, image) {
    // draw active particles
    if (firstActive < firstFree) {
      for (i = firstActive; i < firstFree; i++)
        particles[i].draw(context, image);
    }
    if (firstFree < firstActive) {
      for (i = firstActive; i < particles.length; i++)
        particles[i].draw(context, image);
      for (i = 0; i < firstFree; i++)
        particles[i].draw(context, image);
    }
  };
  return ParticlePool;
})();

/*
 * Putting it all together
 */
(function(canvas) {
  var context = canvas.getContext('2d'),
      particles = new ParticlePool(settings.particles.length),
      particleRate = settings.particles.length / settings.particles.duration, // particles/sec
      time;
  
  // get point on heart with -PI <= t <= PI
  function pointOnHeart(t) {
    return new Point(
      160 * Math.pow(Math.sin(t), 3),
      130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
    );
  }
  
  // creating the particle image using a dummy canvas
  var image = (function() {
    var canvas  = document.createElement('canvas'),
        context = canvas.getContext('2d');
    canvas.width  = settings.particles.size;
    canvas.height = settings.particles.size;
    // helper function to create the path
    function to(t) {
      var point = pointOnHeart(t);
      point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
      point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
      return point;
    }
    // create the path
    context.beginPath();
    var t = -Math.PI;
    var point = to(t);
    context.moveTo(point.x, point.y);
    while (t < Math.PI) {
      t += 0.01; // baby steps!
      point = to(t);
      context.lineTo(point.x, point.y);
    }
    context.closePath();
    // create the fill
    context.fillStyle = '#ea80b0';
    context.fill();
    // create the image
    var image = new Image();
    image.src = canvas.toDataURL();
    return image;
  })();
  
  // render that thing!
  function render() {
    // next animation frame
    requestAnimationFrame(render);
    
    // update time
    var newTime   = new Date().getTime() / 1000,
        deltaTime = newTime - (time || newTime);
    time = newTime;
    
    // clear canvas
    context.clearRect(0, 0, canvas.width, canvas.height);
    
    // create new particles
    var amount = particleRate * deltaTime;
    for (var i = 0; i < amount; i++) {
      var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
      var dir = pos.clone().length(settings.particles.velocity);
      particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
    }
    
    // update and draw particles
    particles.update(deltaTime);
    particles.draw(context, image);
  }
  
  // handle (re-)sizing of the canvas
  function onResize() {
    canvas.width  = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
  }
  window.onresize = onResize;
  
  // delay rendering bootstrap
  setTimeout(function() {
    onResize();
    render();
  }, 10);
})(document.getElementById('pinkboard'));</script>

</body>
</html>


 

2.第二个html

输出示例

调整一样方式

代码如下(这是看这个博主的):

<!DOCTYPE html>
<!-- saved from url=(0033)http://junior-l.gitee.io/to-lili/ -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <title>💗</title>
    <style>
        canvas {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, .2);
        }
    </style>
</head>
<body>

<canvas id="heart" width="1920" height="947"></canvas>
<script>
    window.requestAnimationFrame =
        window.__requestAnimationFrame ||
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        (function () {
            return function (callback, element) {
                var lastTime = element.__lastTime;
                if (lastTime === undefined) {
                    lastTime = 0;
                }
                var currTime = Date.now();
                var timeToCall = Math.max(1, 33 - (currTime - lastTime));
                window.setTimeout(callback, timeToCall);
                element.__lastTime = currTime + timeToCall;
            };
        })();
    window.isDevice = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(((navigator.userAgent || navigator.vendor || window.opera)).toLowerCase()));
    var loaded = false;
    var init = function () {
        if (loaded) return;
        loaded = true;
        var mobile = window.isDevice;
        var koef = mobile ? 0.5 : 1;
        var canvas = document.getElementById('heart');
        var ctx = canvas.getContext('2d');
        var width = canvas.width = koef * innerWidth;
        var height = canvas.height = koef * innerHeight;
        var rand = Math.random;
        ctx.fillStyle = "rgba(0,0,0,1)";
        ctx.fillRect(0, 0, width, height);

        var heartPosition = function (rad) {
            //return [Math.sin(rad), Math.cos(rad)];
            return [Math.pow(Math.sin(rad), 3), -(15 * Math.cos(rad) - 5 * Math.cos(2 * rad) - 2 * Math.cos(3 * rad) - Math.cos(4 * rad))];
        };
        var scaleAndTranslate = function (pos, sx, sy, dx, dy) {
            return [dx + pos[0] * sx, dy + pos[1] * sy];
        };

        window.addEventListener('resize', function () {
            width = canvas.width = koef * innerWidth;
            height = canvas.height = koef * innerHeight;
            ctx.fillStyle = "rgba(0,0,0,1)";
            ctx.fillRect(0, 0, width, height);
        });

        var traceCount = mobile ? 20 : 50;
        var pointsOrigin = [];
        var i;
        var dr = mobile ? 0.3 : 0.1;
        for (i = 0; i < Math.PI * 2; i += dr) pointsOrigin.push(scaleAndTranslate(heartPosition(i), 210, 13, 0, 0));
        for (i = 0; i < Math.PI * 2; i += dr) pointsOrigin.push(scaleAndTranslate(heartPosition(i), 150, 9, 0, 0));
        for (i = 0; i < Math.PI * 2; i += dr) pointsOrigin.push(scaleAndTranslate(heartPosition(i), 90, 5, 0, 0));
        var heartPointsCount = pointsOrigin.length;

        var targetPoints = [];
        var pulse = function (kx, ky) {
            for (i = 0; i < pointsOrigin.length; i++) {
                targetPoints[i] = [];
                targetPoints[i][0] = kx * pointsOrigin[i][0] + width / 2;
                targetPoints[i][1] = ky * pointsOrigin[i][1] + height / 2;
            }
        };

        var e = [];
        for (i = 0; i < heartPointsCount; i++) {
            var x = rand() * width;
            var y = rand() * height;
            e[i] = {
                vx: 0,
                vy: 0,
                R: 2,
                speed: rand() + 5,
                q: ~~(rand() * heartPointsCount),
                D: 2 * (i % 2) - 1,
                force: 0.2 * rand() + 0.7,
                f: "hsla(0," + ~~(40 * rand() + 60) + "%," + ~~(60 * rand() + 20) + "%,.3)",
                trace: []
            };
            for (var k = 0; k < traceCount; k++) e[i].trace[k] = {x: x, y: y};
        }

        var config = {
            traceK: 0.4,
            timeDelta: 0.01
        };

        var time = 0;
        var loop = function () {
            var n = -Math.cos(time);
            pulse((1 + n) * .5, (1 + n) * .5);
            time += ((Math.sin(time)) < 0 ? 9 : (n > 0.8) ? .2 : 1) * config.timeDelta;
            ctx.fillStyle = "rgba(0,0,0,.1)";
            ctx.fillRect(0, 0, width, height);
            for (i = e.length; i--;) {
                var u = e[i];
                var q = targetPoints[u.q];
                var dx = u.trace[0].x - q[0];
                var dy = u.trace[0].y - q[1];
                var length = Math.sqrt(dx * dx + dy * dy);
                if (10 > length) {
                    if (0.95 < rand()) {
                        u.q = ~~(rand() * heartPointsCount);
                    } else {
                        if (0.99 < rand()) {
                            u.D *= -1;
                        }
                        u.q += u.D;
                        u.q %= heartPointsCount;
                        if (0 > u.q) {
                            u.q += heartPointsCount;
                        }
                    }
                }
                u.vx += -dx / length * u.speed;
                u.vy += -dy / length * u.speed;
                u.trace[0].x += u.vx;
                u.trace[0].y += u.vy;
                u.vx *= u.force;
                u.vy *= u.force;
                for (k = 0; k < u.trace.length - 1;) {
                    var T = u.trace[k];
                    var N = u.trace[++k];
                    N.x -= config.traceK * (N.x - T.x);
                    N.y -= config.traceK * (N.y - T.y);
                }
                ctx.fillStyle = u.f;
                for (k = 0; k < u.trace.length; k++) {
                    ctx.fillRect(u.trace[k].x, u.trace[k].y, 1, 1);
                }
            }
            ctx.fillStyle = "rgba(255,255,255,1)";
            for (i = u.trace.length + 13; i--;) ctx.fillRect(targetPoints[i][0], targetPoints[i][1], 2, 2);

            window.requestAnimationFrame(loop, canvas);
        };
        loop();
    };

    var s = document.readyState;
    if (s === 'complete' || s === 'loaded' || s === 'interactive') init();
    else document.addEventListener('DOMContentLoaded', init, false);
</script>

</body></html>

3.第三个html

样子

 

备注

这个我个人感觉还是蛮好看的,值得注意的是,里面的字是也能动的,可以把♥瓜瓜♥改成你想要的字眼(代码里面ctrl+f 找瓜瓜字眼 替换即可),titile也同理

代码

<!DOCTYPE html>
<!-- saved from url=(0046)https://httishere.gitee.io/notion/v4/love-name -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <title>💗 Love you 💗 My Dear 瓜瓜💗</title>
    <style type="text/css">
      body {
        margin: 0;
        overflow: hidden;
        background: #000;
      }
      canvas {
        position: absolute;
        width: 100%;
        height: 100%;
      }
      #pinkboard {
        animation: anim 1.5s ease-in-out infinite;
        -webkit-animation: anim 1.5s ease-in-out infinite;
        -o-animation: anim 1.5s ease-in-out infinite;
        -moz-animation: anim 1.5s ease-in-out infinite;
      }
      @keyframes anim {
        0% {
          transform: scale(0.8);
        }
        25% {
          transform: scale(0.7);
        }
        50% {
          transform: scale(1);
        }
        75% {
          transform: scale(0.7);
        }
        100% {
          transform: scale(0.8);
        }
      }
      @-webkit-keyframes anim {
        0% {
          -webkit-transform: scale(0.8);
        }
        25% {
          -webkit-transform: scale(0.7);
        }
        50% {
          -webkit-transform: scale(1);
        }
        75% {
          -webkit-transform: scale(0.7);
        }
        100% {
          -webkit-transform: scale(0.8);
        }
      }
      @-o-keyframes anim {
        0% {
          -o-transform: scale(0.8);
        }
        25% {
          -o-transform: scale(0.7);
        }
        50% {
          -o-transform: scale(1);
        }
        75% {
          -o-transform: scale(0.7);
        }
        100% {
          -o-transform: scale(0.8);
        }
      }
      @-moz-keyframes anim {
        0% {
          -moz-transform: scale(0.8);
        }
        25% {
          -moz-transform: scale(0.7);
        }
        50% {
          -moz-transform: scale(1);
        }
        75% {
          -moz-transform: scale(0.7);
        }
        100% {
          -moz-transform: scale(0.8);
        }
      }
      #name {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        margin-top: -20px;
        font-size: 46px;
        color: #ea80b0;
      }
    </style>
  </head>
  <body>
    <canvas id="pinkboard" width="1920" height="947"></canvas>
    <!-- <div id="name">瓜瓜💗 ❤️</div> -->
    <canvas id="canvas" width="1920" height="947"></canvas>

    <script type="text/javascript">
      const colors = [
        "#eec996",
        "#8fb7d3",
        "#b7d4c6",
        "#c3bedd",
        "#f1d5e4",
        "#cae1d3",
        "#f3c89d",
        "#d0b0c3",
        "#819d53",
        "#c99294",
        "#cec884",
        "#ff8e70",
        "#e0a111",
        "#fffdf6",
        "#cbd7ac",
        "#e8c6c0",
        "#dc9898",
        "#ecc8ba",
      ]; //用来设置的颜色
      var canvas = document.getElementById("canvas");
      var ctx = canvas.getContext("2d");
      let count = 1;

      var ww = window.innerWidth;
      var wh = window.innerHeight;

      var hearts = [];

      function init() {
        requestAnimationFrame(render);
        canvas.width = ww;
        canvas.height = wh;
        for (var i = 0; i < 100; i++) {
          hearts.push(new Heart());
        }
      }

      function Heart() {
        this.x = Math.random() * ww;
        this.y = Math.random() * wh;
        this.opacity = Math.random() * 0.5 + 0.5;
        this.vel = {
          x: (Math.random() - 0.5) * 4,
          y: (Math.random() - 0.5) * 4,
        };
        this.targetScale = Math.random() * 0.15 + 0.02;
        this.scale = this.targetScale * Math.random();
      }

      Heart.prototype.update = function (i) {
        this.x += this.vel.x;
        this.y += this.vel.y;

        this.scale += (this.targetScale - this.scale) * 0.01;
        if (this.x - this.width > ww || this.x + this.width < 0) {
          this.scale = 0;
          this.x = Math.random() * ww;
        }
        if (this.y - this.height > wh || this.y + this.height < 0) {
          this.scale = 0;
          this.y = Math.random() * wh;
        }
        this.width = 473.8;
        this.height = 408.6;
      };
      Heart.prototype.draw = function (i) {
        ctx.globalAlpha = this.opacity;
        ctx.font = `${180 * this.scale}px "微软雅黑"`;
        // ctx.font="20px";
        ctx.fillStyle = colors[i % 18];
        ctx.fillText(
          "💗瓜瓜💗",
          this.x - this.width * 0.5,
          this.y - this.height * 0.5,
          this.width,
          this.height
        );
        // ctx.drawImage(
        //   heartImage,
        //   this.x - this.width * 0.5,
        //   this.y - this.height * 0.5,
        //   this.width,
        //   this.height
        // );
      };

      function render() {
        ctx.clearRect(0, 0, ww, wh);
        // ctx.globalAlpha = 1;
        // ctx.fillStyle = "rgba(255,255,255,0.3)";
        // ctx.fillRect(0, 0, ww, wh);
        for (var i = 0; i < 100; i++) {
          hearts[i].update(i);
          hearts[i].draw(i);
        }
        requestAnimationFrame(render);
      }
      init();

      // var heartImage = new Image();
      // heartImage.onload = init();
      // heartImage.src =
      //   "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0NzMuOHB4IiBoZWlnaHQ9IjQwOC42cHgiIHZpZXdCb3g9IjAgMCA0NzMuOCA0MDguNiI+PHBhdGggZmlsbD0iI2QzMjkzMiIgZD0iTTQwNC42LDE2LjZDMzg1LjQsNi4xLDM2My41LDAsMzQwLDBjLTQxLjUsMC03OC41LDE4LjktMTAzLDQ4LjVDMjEyLjMsMTguOSwxNzUuMywwLDEzMy44LDAgYy0yMy4zLDAtNDUuMyw2LjEtNjQuNSwxNi42QzI3LjksMzkuNSwwLDgzLjQsMCwxMzMuOWMwLDE0LjQsMi40LDI4LjMsNi42LDQxLjJDMjkuNiwyNzguNCwyMzcsNDA4LjYsMjM3LDQwOC42IHMyMDcuMi0xMzAuMiwyMzAuMi0yMzMuNWM0LjMtMTIuOSw2LjYtMjYuOCw2LjYtNDEuMkM0NzMuOCw4My40LDQ0NS45LDM5LjYsNDA0LjYsMTYuNnoiLz48L3N2Zz4=";

      window.addEventListener("resize", function () {
        ww = window.innerWidth;
        wh = window.innerHeight;
      });
    </script>
    <script>
      /*
       * Settings
       */
      var settings = {
        particles: {
          length: 500, // maximum amount of particles
          duration: 2, // particle duration in sec
          velocity: 100, // particle velocity in pixels/sec
          effect: -0.75, // play with this for a nice effect
          size: 30, // particle size in pixels
        },
      };

      /*
       * RequestAnimationFrame polyfill by Erik M?ller
       */
      (function () {
        var b = 0;
        var c = ["ms", "moz", "webkit", "o"];
        for (var a = 0; a < c.length && !window.requestAnimationFrame; ++a) {
          window.requestAnimationFrame = window[c[a] + "RequestAnimationFrame"];
          window.cancelAnimationFrame =
            window[c[a] + "CancelAnimationFrame"] ||
            window[c[a] + "CancelRequestAnimationFrame"];
        }
        if (!window.requestAnimationFrame) {
          window.requestAnimationFrame = function (h, e) {
            var d = new Date().getTime();
            var f = Math.max(0, 16 - (d - b));
            var g = window.setTimeout(function () {
              h(d + f);
            }, f);
            b = d + f;
            return g;
          };
        }
        if (!window.cancelAnimationFrame) {
          window.cancelAnimationFrame = function (d) {
            clearTimeout(d);
          };
        }
      })();

      /*
       * Point class
       */
      var Point = (function () {
        function Point(x, y) {
          this.x = typeof x !== "undefined" ? x : 0;
          this.y = typeof y !== "undefined" ? y : 0;
        }
        Point.prototype.clone = function () {
          return new Point(this.x, this.y);
        };
        Point.prototype.length = function (length) {
          if (typeof length == "undefined")
            return Math.sqrt(this.x * this.x + this.y * this.y);
          this.normalize();
          this.x *= length;
          this.y *= length;
          return this;
        };
        Point.prototype.normalize = function () {
          var length = this.length();
          this.x /= length;
          this.y /= length;
          return this;
        };
        return Point;
      })();

      /*
       * Particle class
       */

      var Particle = (function () {
        function Particle() {
          this.position = new Point();
          this.velocity = new Point();
          this.acceleration = new Point();
          this.age = 0;
        }
        Particle.prototype.initialize = function (x, y, dx, dy) {
          this.position.x = x;
          this.position.y = y;
          this.velocity.x = dx;
          this.velocity.y = dy;
          this.acceleration.x = dx * settings.particles.effect;
          this.acceleration.y = dy * settings.particles.effect;
          this.age = 0;
        };
        Particle.prototype.update = function (deltaTime) {
          this.position.x += this.velocity.x * deltaTime;
          this.position.y += this.velocity.y * deltaTime;
          this.velocity.x += this.acceleration.x * deltaTime;
          this.velocity.y += this.acceleration.y * deltaTime;
          this.age += deltaTime;
        };
        Particle.prototype.draw = function (context, image) {
          function ease(t) {
            return --t * t * t + 1;
          }
          var size = image.width * ease(this.age / settings.particles.duration);
          context.globalAlpha = 1 - this.age / settings.particles.duration;
          context.drawImage(
            image,
            this.position.x - size / 2,
            this.position.y - size / 2,
            size,
            size
          );
        };
        return Particle;
      })();

      /*
       * ParticlePool class
       */
      var ParticlePool = (function () {
        var particles,
          firstActive = 0,
          firstFree = 0,
          duration = settings.particles.duration;

        function ParticlePool(length) {
          // create and populate particle pool
          particles = new Array(length);
          for (var i = 0; i < particles.length; i++)
            particles[i] = new Particle();
        }
        ParticlePool.prototype.add = function (x, y, dx, dy) {
          particles[firstFree].initialize(x, y, dx, dy);

          // handle circular queue
          firstFree++;
          if (firstFree == particles.length) firstFree = 0;
          if (firstActive == firstFree) firstActive++;
          if (firstActive == particles.length) firstActive = 0;
        };
        ParticlePool.prototype.update = function (deltaTime) {
          var i;

          // update active particles
          if (firstActive < firstFree) {
            for (i = firstActive; i < firstFree; i++)
              particles[i].update(deltaTime);
          }
          if (firstFree < firstActive) {
            for (i = firstActive; i < particles.length; i++)
              particles[i].update(deltaTime);
            for (i = 0; i < firstFree; i++) particles[i].update(deltaTime);
          }

          // remove inactive particles
          while (
            particles[firstActive].age >= duration &&
            firstActive != firstFree
          ) {
            firstActive++;
            if (firstActive == particles.length) firstActive = 0;
          }
        };
        ParticlePool.prototype.draw = function (context, image) {
          // draw active particles
          if (firstActive < firstFree) {
            for (i = firstActive; i < firstFree; i++)
              particles[i].draw(context, image);
          }
          if (firstFree < firstActive) {
            for (i = firstActive; i < particles.length; i++)
              particles[i].draw(context, image);
            for (i = 0; i < firstFree; i++) particles[i].draw(context, image);
          }
        };
        return ParticlePool;
      })();

      /*
       * Putting it all together
       */
      (function (canvas) {
        var context = canvas.getContext("2d"),
          particles = new ParticlePool(settings.particles.length),
          particleRate =
            settings.particles.length / settings.particles.duration, // particles/sec
          time;

        // get point on heart with -PI <= t <= PI
        function pointOnHeart(t) {
          return new Point(
            160 * Math.pow(Math.sin(t), 3),
            130 * Math.cos(t) -
              50 * Math.cos(2 * t) -
              20 * Math.cos(3 * t) -
              10 * Math.cos(4 * t) +
              25
          );
        }

        // creating the particle image using a dummy canvas
        var image = (function () {
          var canvas = document.createElement("canvas"),
            context = canvas.getContext("2d");
          canvas.width = settings.particles.size;
          canvas.height = settings.particles.size;
          // helper function to create the path
          function to(t) {
            var point = pointOnHeart(t);
            point.x =
              settings.particles.size / 2 +
              (point.x * settings.particles.size) / 350;
            point.y =
              settings.particles.size / 2 -
              (point.y * settings.particles.size) / 350;
            return point;
          }
          // create the path
          context.beginPath();
          var t = -Math.PI;
          var point = to(t);
          context.moveTo(point.x, point.y);
          while (t < Math.PI) {
            t += 0.01; // baby steps!
            point = to(t);
            context.lineTo(point.x, point.y);
          }
          context.closePath();
          // create the fill
          context.fillStyle = "#ea80b0";
          context.fill();
          // create the image
          var image = new Image();
          image.src = canvas.toDataURL();
          return image;
        })();

        // render that thing!
        function render() {
          // next animation frame
          requestAnimationFrame(render);

          // update time
          var newTime = new Date().getTime() / 1000,
            deltaTime = newTime - (time || newTime);
          time = newTime;

          // clear canvas
          context.clearRect(0, 0, canvas.width, canvas.height);

          // create new particles
          var amount = particleRate * deltaTime;
          for (var i = 0; i < amount; i++) {
            var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
            var dir = pos.clone().length(settings.particles.velocity);
            particles.add(
              canvas.width / 2 + pos.x,
              canvas.height / 2 - pos.y,
              dir.x,
              -dir.y
            );
          }

          // update and draw particles
          particles.update(deltaTime);
          particles.draw(context, image);
        }

        // handle (re-)sizing of the canvas
        function onResize() {
          canvas.width = canvas.clientWidth;
          canvas.height = canvas.clientHeight;
        }
        window.onresize = onResize;

        // delay rendering bootstrap
        setTimeout(function () {
          onResize();
          render();
        }, 10);
      })(document.getElementById("pinkboard"));

      // 参考:https://blog.csdn.net/weixin_57038822/article/details/121644240
    </script>
  

</body></html>

3.第四个html

样例

 代码调整思路

x位置直接记事本打开ctrl+f 找亲爱的 编辑文案

然后对这行字的编辑(样式上)

是这个,改这里的信息就行哪个参数不会就搜一下他的作用 比如第一行是字体,你可以百度html字体 比如这个大佬写的博客,都是一样道理。

代码

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<head>
    <title>LoveHTT</title>
</head>
<body> <canvas id="canvas"></canvas>
<style type="text/css">
    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
    }
</style>
<script type="text/javascript">
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
 
 
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
 
    var texts = 'I LOVE U'.split('');
 
    var fontSize = 16;
    var columns = canvas.width / fontSize;
    // 用于计算输出文字时坐标,所以长度即为列数
    var drops = [];
    //初始值
    for (var x = 0; x < columns; x++) {
        drops[x] = 1;
    }
 
    function draw() {
        //让背景逐渐由透明到不透明
        ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //文字颜色
        ctx.fillStyle = '#f584b7';
        ctx.font = fontSize + 'px arial';
        //逐行输出文字
        for (var i = 0; i < drops.length; i++) {
            var text = texts[Math.floor(Math.random() * texts.length)];
            ctx.fillText(text, i * fontSize, drops[i] * fontSize);
 
            if (drops[i] * fontSize > canvas.height || Math.random() > 0.95) {
                drops[i] = 0;
            }
 
            drops[i]++;
        }
    }
    setInterval(draw, 33);
</script>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
    <TITLE> love</TITLE>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
    <META NAME="Generator" CONTENT="EditPlus">
    <META NAME="Author" CONTENT="">
    <META NAME="Keywords" CONTENT="">
    <META NAME="Description" CONTENT="">
    <meta charset="UTF-8">
    <style>
        html, body {
            height: 100%;
            padding: 0;
            margin: 0;
            background: rgb(0, 0, 0);
        }
        canvas {
            position: absolute;
            width: 100%;
            height: 100%;
        }
        #child{
            position: fixed;
            top:50%;
            left: 50%;
            margin-top: -75px;
            margin-left:-100px ;
 
        }
 
        h4{font-family:"STKaiti";
             font-size: 40px;
             color:#f584b7;
             position: relative;
             top: -70px;left: -65px;}
    </style>
</head>
<body>
<div id="child" ><h4>💗致亲爱的X女士</h4></div><!--这里写名字❤!!!-->
  <canvas id ="pinkboard"></canvas>
  <!-- <canvas id= "canvas"></canvas>  -->
<script>
    /*
   * Settings
   */
    var settings = {
        particles: {
            length:   500, // maximum amount of particles
            duration:   2, // particle duration in sec
            velocity: 100, // particle velocity in pixels/sec
            effect: -0.75, // play with this for a nice effect
            size:      30, // particle size in pixels
        },
    };
 
    /*
     * RequestAnimationFrame polyfill by Erik Möller
     */
    (function(){var b=0;var c=["ms","moz","webkit","o"];for(var a=0;a<c.length&&!window.requestAnimationFrame;++a){window.requestAnimationFrame=window[c[a]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[c[a]+"CancelAnimationFrame"]||window[c[a]+"CancelRequestAnimationFrame"]}if(!window.requestAnimationFrame){window.requestAnimationFrame=function(h,e){var d=new Date().getTime();var f=Math.max(0,16-(d-b));var g=window.setTimeout(function(){h(d+f)},f);b=d+f;return g}}if(!window.cancelAnimationFrame){window.cancelAnimationFrame=function(d){clearTimeout(d)}}}());
 
    /*
     * Point class
     */
    var Point = (function() {
        function Point(x, y) {
            this.x = (typeof x !== 'undefined') ? x : 0;
            this.y = (typeof y !== 'undefined') ? y : 0;
        }
        Point.prototype.clone = function() {
            return new Point(this.x, this.y);
        };
        Point.prototype.length = function(length) {
            if (typeof length == 'undefined')
                return Math.sqrt(this.x * this.x + this.y * this.y);
            this.normalize();
            this.x *= length;
            this.y *= length;
            return this;
        };
        Point.prototype.normalize = function() {
            var length = this.length();
            this.x /= length;
            this.y /= length;
            return this;
        };
        return Point;
    })();
 
    /*
     * Particle class
     */
    var Particle = (function() {
        function Particle() {
            this.position = new Point();
            this.velocity = new Point();
            this.acceleration = new Point();
            this.age = 0;
        }
        Particle.prototype.initialize = function(x, y, dx, dy) {
            this.position.x = x;
            this.position.y = y;
            this.velocity.x = dx;
            this.velocity.y = dy;
            this.acceleration.x = dx * settings.particles.effect;
            this.acceleration.y = dy * settings.particles.effect;
            this.age = 0;
        };
        Particle.prototype.update = function(deltaTime) {
            this.position.x += this.velocity.x * deltaTime;
            this.position.y += this.velocity.y * deltaTime;
            this.velocity.x += this.acceleration.x * deltaTime;
            this.velocity.y += this.acceleration.y * deltaTime;
            this.age += deltaTime;
        };
        Particle.prototype.draw = function(context, image) {
            function ease(t) {
                return (--t) * t * t + 1;
            }
            var size = image.width * ease(this.age / settings.particles.duration);
            context.globalAlpha = 1 - this.age / settings.particles.duration;
            context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
        };
        return Particle;
    })();
 
    /*
     * ParticlePool class
     */
    var ParticlePool = (function() {
        var particles,
            firstActive = 0,
            firstFree   = 0,
            duration    = settings.particles.duration;
 
        function ParticlePool(length) {
            // create and populate particle pool
            particles = new Array(length);
            for (var i = 0; i < particles.length; i++)
                particles[i] = new Particle();
        }
        ParticlePool.prototype.add = function(x, y, dx, dy) {
            particles[firstFree].initialize(x, y, dx, dy);
 
            // handle circular queue
            firstFree++;
            if (firstFree   == particles.length) firstFree   = 0;
            if (firstActive == firstFree       ) firstActive++;
            if (firstActive == particles.length) firstActive = 0;
        };
        ParticlePool.prototype.update = function(deltaTime) {
            var i;
 
            // update active particles
            if (firstActive < firstFree) {
                for (i = firstActive; i < firstFree; i++)
                    particles[i].update(deltaTime);
            }
            if (firstFree < firstActive) {
                for (i = firstActive; i < particles.length; i++)
                    particles[i].update(deltaTime);
                for (i = 0; i < firstFree; i++)
                    particles[i].update(deltaTime);
            }
 
            // remove inactive particles
            while (particles[firstActive].age >= duration && firstActive != firstFree) {
                firstActive++;
                if (firstActive == particles.length) firstActive = 0;
            }
 
 
        };
        ParticlePool.prototype.draw = function(context, image) {
            // draw active particles
            if (firstActive < firstFree) {
                for (i = firstActive; i < firstFree; i++)
                    particles[i].draw(context, image);
            }
            if (firstFree < firstActive) {
                for (i = firstActive; i < particles.length; i++)
                    particles[i].draw(context, image);
                for (i = 0; i < firstFree; i++)
                    particles[i].draw(context, image);
            }
        };
        return ParticlePool;
    })();
 
    /*
     * Putting it all together
     */
    (function(canvas) {
        var context = canvas.getContext('2d'),
            particles = new ParticlePool(settings.particles.length),
            particleRate = settings.particles.length / settings.particles.duration, // particles/sec
            time;
 
        // get point on heart with -PI <= t <= PI
        function pointOnHeart(t) {
            return new Point(
                160 * Math.pow(Math.sin(t), 3),
                130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
            );
        }
 
        // creating the particle image using a dummy canvas
        var image = (function() {
            var canvas  = document.createElement('canvas'),
                context = canvas.getContext('2d');
            canvas.width  = settings.particles.size;
            canvas.height = settings.particles.size;
            // helper function to create the path
            function to(t) {
                var point = pointOnHeart(t);
                point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
                point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
                return point;
            }
            // create the path
            context.beginPath();
            var t = -Math.PI;
            var point = to(t);
            context.moveTo(point.x, point.y);
            while (t < Math.PI) {
                t += 0.01; // baby steps!
                point = to(t);
                context.lineTo(point.x, point.y);
            }
            context.closePath();
            // create the fill
            context.fillStyle = '#ea80b0';
            context.fill();
            // create the image
            var image = new Image();
            image.src = canvas.toDataURL();
            return image;
        })();
 
        // render that thing!
        function render() {
            // next animation frame
            requestAnimationFrame(render);
 
            // update time
            var newTime   = new Date().getTime() / 1000,
                deltaTime = newTime - (time || newTime);
            time = newTime;
 
            // clear canvas
            context.clearRect(0, 0, canvas.width, canvas.height);
 
            // create new particles
            var amount = particleRate * deltaTime;
            for (var i = 0; i < amount; i++) {
                var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
                var dir = pos.clone().length(settings.particles.velocity);
                particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
            }
 
            // update and draw particles
            particles.update(deltaTime);
            particles.draw(context, image);
        }
 
        // handle (re-)sizing of the canvas
        function onResize() {
            canvas.width  = canvas.clientWidth;
            canvas.height = canvas.clientHeight;
        }
        window.onresize = onResize;
 
        // delay rendering bootstrap
        setTimeout(function() {
            onResize();
            render();
        }, 10);
    })(document.getElementById('pinkboard'));
	
	
	
	
</script>
 
</BODY>
 <!--                           
<audio controls>
  <source src="Alan Walker-Faded.mp3" type="audio/ogg">
  <source src="Alan Walker-Faded.mp3" type="audio/mpeg">
</audio >

     -->
 
		
</HTML>

总结

本文简单介绍了几种爱心代码,希望对大家有所帮助,求赞欧~~~
另外,python想送给你的那个 TA的话可以打包为exe的,我后期再补一下教程,然后运行有问题的可以在评论区说明~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/38422.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【iOS】—— 编译链接

【iOS】—— 编译链接 文章目录 【iOS】—— 编译链接编译流程预处理&#xff08;预编译Prepressing&#xff09;编译&#xff08;Compilation&#xff09;汇编&#xff08;Assembly&#xff09;链接&#xff08;Linking&#xff09; 编译流程 编译流程分为四步 预处理&#…

python 安装、配置、使用 xlrd模块、numpy模块

目录 一、xlrd模块 &#xff08;一&#xff09;安装xlrd模块 &#xff08;二&#xff09; pycharm 配置xlrd &#xff08;三&#xff09; 读取xls格式 &#xff08;四&#xff09;xlrd读取时间日期时&#xff0c;会是float类型&#xff0c;需要转换。 二、numpy模块 (一)n…

基于linux下的高并发服务器开发(第一章)- Linux系统IO函数

05 / Linux系统IO函数 &#xff08;1&#xff09;man 2 open >>打开一个已经存在的文件 int open(const char *pathname, int flags); 参数&#xff1a; pathname:要打开文件路径 - flags:对文件的操作权限设置还有其他的设置 O_RDONLY,O_WRONLY,O_RDWR 这三个设置是互斥…

数据结构——各种常见算法的实现方法和思路

文章目录 常见的排序算法类型复杂度和稳定性 1.冒泡排序2.直接插入排序3.希尔排序4.简单选择排序方法1&#xff1a;双向遍历选择排序方法2&#xff1a;单向遍历选择排序 5.归并排序方法1&#xff1a;递归方法2&#xff1a;非递归 6.快速排序方法1&#xff1a;随机取keyi方法2&a…

leetcode 17. 电话号码的字母组合

2023.7.18 该题也是经典回溯题。 与之前做的组合有两点不同&#xff1a; 之前的组合题是求同一集合的组合&#xff0c;而本题是求不同集合的组合。本题还需要有一个将字符串数字转换为手机号9键对应字符集的过程。 下面上代码&#xff1a; class Solution { public:string le…

C# 连接mysql数据库报错:Character set ‘utf8mb3‘ is not supported by .Net Framework.

最近项目突然连接mysql数据库出现一个bug&#xff0c;排查了半小时&#xff0c;最后更新MySql.Data版本解决了&#xff0c;错误信息如下&#xff1a; System.NotSupportedException: Character set utf8mb3 is not supported by .Net Framework.在 MySql.Data.MySqlClient.Cha…

学习PostgreSQL的优势

学习 PostgreSQL 可以为您打开许多就业机会。 PostgreSQL 是一种强大的关系型数据库管理系统&#xff0c;被广泛用于企业和组织中的数据管理和应用程序开发。 以下是一些学习 PostgreSQL 可能帮助您找到的工作领域&#xff1a; **1.数据库管理员&#xff1a;**作为 PostgreSQ…

element 文件批量上传展示上传结果、失败重新上传

效果图&#xff1a; 不废话了&#xff0c;直接上代码&#xff01;&#xff01;&#xff01; HTML部分&#xff1a; <template><div class"container"><el-uploadclass"upload-demo"accept".jpg,.JPG,.png,.PNG"action"#&q…

浅谈物联网在电力行业的应用

摘要&#xff1a;随着社会经济的快速发展&#xff0c;物联网技术也在各个行业中得到了广泛的应用&#xff0c;特别是在电力行业中应用物联网技术&#xff0c;也有效的促进了电力行业的现代化发展。而物联网与智能电网同样都是当代重要的高新技术以及新兴产业。所以通过对于物联…

【论文阅读】《Distilling the Knowledge in a Neural Network》

【论文阅读】《Distilling the Knowledge in a Neural Network》 推荐指数&#xff1a; 1. 动机 &#xff08;1&#xff09;虽然一个ensemble的模型可以提升模型的效果&#xff0c;但是在效率方面实在难以接受&#xff0c;尤其是在每个模型都是一个大型的网络模型的时候。 &…

共筑开源新长城 龙蜥社区走进开放原子校源行-清华大学站

6 月 28 日&#xff0c;以“聚缘于校&#xff0c;开源共行”为主题的 2023 年开放原子校源行活动在清华大学成功举行。本次活动由开放原子开源基金会和清华大学共同主办&#xff0c;来自各行业的 22 位大咖共聚校园共话开源。龙蜥社区技术专家边子政受邀进行技术分享&#xff0…

多元线性回归的梯度下降法

多维特征&#xff08;其实就是从单变量变成了多变量&#xff09; 目前为止&#xff0c;我们探讨了单变量/特征的回归模型&#xff0c;现在我们对房价模型增加更多的特征&#xff0c;例如房间数楼层等&#xff0c;构成一个含有多个变量的模型&#xff0c;模型中的特征为。 增添…

hadoop --- MapReduce

MapReduce定义&#xff1a; MapReduce可以分解为Map (映射) Reduce (规约) &#xff0c; 具体过程&#xff1a; Map : 输入数据集被切分成多个小块&#xff0c;并分配给不同的计算节点进行处理Shuffle and Sort&#xff1a;洗牌和排序&#xff0c;在 Map 阶段结束后&#xf…

Versal ACAP在线升级之Boot Image格式

1、简介 Xilinx FPGA、SOC器件和自适应计算加速平台&#xff08;ACAPs&#xff09;通常由多个硬件和软件二进制文件组成&#xff0c;用于启动这些设备后按照预期设计进行工作。这些二进制文件可以包括FPGA比特流、固件镜像、bootloader引导程序、操作系统和用户选择的应…

使用nginx部署前后端分离项目,处理跨域问题(共享cookie)

1.唠嗑 踩坑了&#xff0c;花费一天时间&#xff0c;开始对nginx配置不懂&#xff0c;老是弄错了配置文件&#xff0c;之前装的nginx ,cofnig有两个&#xff0c;nginx.config和nginx.config.def &#xff0c;开始配置我在nginx.config中配置的&#xff0c;后面一直在改def&…

谈谈VPN是什么、类型、使用场景、工作原理

作者&#xff1a;Insist-- 个人主页&#xff1a;insist--个人主页 作者会持续更新网络知识和python基础知识&#xff0c;期待你的关注 前言 本文将讲解VPN是什么、以及它的类型、使用场景、工作原理。 目录 一、VPN是什么&#xff1f; 二、VPN的类型 1、站点对站点VPN 2、…

「车型分析」控制系统典型应用车型 —— 停车机器人

如今&#xff0c;城市可用土地的日益稀缺&#xff08;城市化&#xff09;和汽车使用数量的增加&#xff08;机动化&#xff09;,为了可持续性发展和其他生活质量问题相结合&#xff0c;由此孕育出来了一种自动停车系统。停车机器人凭借其灵活、高效、标准化的停车模式&#xff…

day27 贪心算法

1.什么是贪心&#xff1f; 比如10张钞票&#xff0c;有1&#xff0c;5&#xff0c;20&#xff0c;100等面额&#xff0c;取五张&#xff0c;如何取得到数额最多的钱&#xff1f;每次取面额最大的那张钞票&#xff1b;就是每个阶段的局部最优&#xff1b;全局最优就是最后拿到的…

【高并发网络通信架构】3.引入IO多路复用(select,poll,epoll)实现高并发tcp服务端

目录 一&#xff0c;往期文章 二&#xff0c;基本概念 IO多路复用 select 模型 poll 模型 epoll 模型 select&#xff0c;poll&#xff0c;epoll 三者对比 三&#xff0c;函数清单 1.select 方法 2.fd_set 结构体 3.poll 方法 4.struct pollfd 结构体 5.epoll_cre…

plt绘图绘制主次刻度线

这里主要是介绍的坐标轴上的主次刻度的划分&#xff0c;这里需要单独引入ticker中的两个模块进行设置 MultipleLocator, FormatStrFormatter set_major_locator() 设置主刻度set_minor_locator() 设置次刻度set_major_formatter() 设置主刻度格式plt.NullLocator() 删除刻度显…