活动地址:CSDN21天学习挑战赛

用代码写出浪漫合集(爱心、玫瑰花)

     

本文目录:

​一、前言

二、用python、matplotlib、Matlab、java绘制爱心

(1)爱心图形1(弧线型)(显示的文字写在代码里)

(2)爱心图形2(直线型)(显示的文字写在代码里)

(3)爱心图形3(弧线型)(通过输入方式显示文字)

(4)用python绘制爱心树

(5)用matplotlib绘制一颗2D的红心

(6)三维爱心

(7)Matlab 3D心形代码

(8)双心(java)

(9)C语言动态爱心代码

(10)、Python《点燃我温暖你》李峋爱心代码

三、用python、java字符画绘制爱心

(1)一行代码画爱心

(2)用字符输出 I 爱 U (2种形式)

(3)输出五个爱心,由Dear I love you forever! 五个单词填充而成

(4).java 实现 ❤

四、绘制玫瑰花

(1)、6种python玫瑰花绘图源码(立体多层玫瑰、红玫瑰)

(2)、前端canvas玫瑰花

五、前端特效爱心

(1)前端 CSS "I Love You "爱心效果

(2)各国语言“爱”字组成爱心效果

(3)上升爱心效果

(4)变幻爱心

(5)红心下落动画

(6)《点燃我温暖你》中李峋的爱心代码

六、特色推荐


​一、前言

  有缘遇到真心对你好的人不容易,像父母、朋友、真爱你的人,如果遇到了,请好好珍惜,因为有时,有些你想象不到的事情会突然发生,如果遇到了,请别慌乱害怕,那些真心对你的人会陪在你身边和你一起度过最难熬的日子,所以请抓住每一分每一秒,好好对待身边人,凡事别计较太多,把心放宽。在你遇到。。。时,请记住,你并不是唯一一个,这世界上有很多人正在经历着和你一样的事情,虽然他们没有或者无法说出来。

  命始于缘分,爱忠于坚守,情长于陪伴,珍惜每一次相识,珍惜每一分温暖,生活细细品味,真情慢慢体会,不枉此生。

  这里搜集了一些爱心和玫瑰花的代码,供大家学习参考。代码版权属原作者。

二、用python、matplotlib、Matlab、java绘制爱心

python 绘制爱心图片索引:

8、最先复现李峋爱心代码的作者 9、跳动爱心 10、爱心

5、粒子组成爱心,中间加字

6、粒子组成爱心

7、粒子组成爱心

1、(弧线型)(显示文字)

2、(直线型)(显示文字)

3、(弧线型)(输入显示文字)

4、爱心树

python字符画爱心

(1)一行代码画爱心 (2)用字符输出 I 爱 U (2种形式) (2)用字符输出 I 爱 U (2种形式)

(3)输出五个爱心(Dear I love you forever! )五个单词填充而成 (4)爱心 (5)爱心

因数量增加,页面篇幅太长,python 绘制的爱心将更新至此新页面,想查看python爱心绘图的请点击以下链接:

python爱心源代码集锦

(1)爱心图形1(弧线型)(显示的文字写在代码里)

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

import turtle
import time
def LittleHeart():for i in range(200):turtle.right(1)turtle.forward(2)# love = input('请输入表白语句,然后回车,默认为"I Love You":\n')
# me = input('请输入要表白的人:\n')
# if love=='':
# # 如果未输入表白语句,则使用默认语句
#     love='I Love you'love='I Love you'
me = '卧槽,这年轻人。'turtle.setup(width=900,height=600)  # 爱心的画布的大小
turtle.color('red','red')          # 爱心的颜色及外边笔的颜色
turtle.pensize(5)                   # 画笔的粗细
turtle.speed(1000000)               # 绘制速度turtle.up()                         # 画笔向上turtle.hideturtle()
turtle.goto(0,-180)
turtle.showturtle()
turtle.down()
turtle.speed(5)
turtle.begin_fill()# 开始填充
turtle.left(140)
turtle.forward(224)
LittleHeart()
turtle.left(120)
LittleHeart()
turtle.forward(224)
turtle.end_fill()
turtle.pensize(5)
turtle.up()
turtle.hideturtle()
turtle.goto(0,0)
turtle.showturtle()
turtle.color('#CD5C5C','pink')
turtle.write(love,font=('gungsuh',30,),align="center")
turtle.up()
turtle.hideturtle()if me !='':turtle.color('black', 'pink')time.sleep(2)turtle.goto(180,-180)turtle.showturtle()turtle.write(me, font=(20,), align="center", move=True)window=turtle.Screen()window.exitonclick()

(2)爱心图形2(直线型)(显示的文字写在代码里)

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

import turtle
import math
turtle.pen()
t=turtle
t.up()
t.goto(0,150)
t.down()
t.color('red')
t.begin_fill()
t.fillcolor('red')
t.speed(1)
t.left(45)
t.forward(150)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(250+math.sqrt(2)*100)
t.right (90)
t.speed(2)
t.forward(250+100*math.sqrt(2))
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(100)
t.right(45)
t.forward(150)
t.end_fill()
t.goto(-10,0)
t.pencolor('white')
# L
t.pensize(10)
t.goto(-50,0)
t.goto(-50,80)
t.up ()
# I
t.goto(-100,0)
t.down()
t.goto(-160,0)
t.goto(-130,0)
t.goto(-130,80)
t.goto(-160,80)
t.goto(-100,80)
t.up()
# O
t.goto(10,25)
t.down()
t.right(45)
t.circle(25,extent=180)
t.goto(60,55)
t.circle(25,extent=180)
t.goto(10,25)
t.up()
t.goto(75,80)
t.down()
t.goto(100,0)
t.goto(125,80)
t.up()
t.goto(180,80)
t.down()
t.goto(140,80)
t.goto(140,0)
t.goto(180,0)
t.up()
t.goto(180,40)
t.down()
t.goto(140,40)
# U
t.up()
t.goto(-40,-30)
t.down()
t.goto(-40,-80)
t.circle(40,extent=180)
t.goto(40,-30)
t.hideturtle()window=turtle.Screen()
window.exitonclick()

(3)爱心图形3(弧线型)(通过输入方式显示文字)

请输入表白语句,然后回车,(例如"I Love You"):

请输入要表白的人(例如"李思思"):

转载地址:https://changxin.blog.csdn.net/article/details/109842795

# coding: utf-8
import turtle
import time
def LittleHeart():for i in range(200):turtle.right(1)turtle.forward(2)
love=input('请输入表白语句,然后回车,(例如"I Love You"):\n')
me=input('请输入要表白的人(例如"李思思"):\n')
if love=='':                    love='I Love you'
turtle.setup(width=900,height=600)
turtle.color('red','pink')
turtle.pensize(15)
turtle.speed(1000)turtle.up()turtle.hideturtle()
turtle.goto(0,-180)
turtle.showturtle()
turtle.down()
turtle.speed(500)
turtle.begin_fill()
turtle.left(140)
turtle.forward(224)
LittleHeart()
turtle.left(120)
LittleHeart()
turtle.forward(224)
turtle.end_fill()
turtle.pensize(12)
turtle.up()
turtle.hideturtle()
turtle.goto(0,-20)
turtle.showturtle()
turtle.color('#CD5C5C','pink')
turtle.write(love,font=('gungsuh',50,),align="center")
turtle.up()
turtle.hideturtle()
if me !='':turtle.color('black', 'pink')time.sleep(1)
turtle.goto(180,-180)
turtle.showturtle()
turtle.write(me, font=(20,25), align="center", move=True)
window=turtle.Screen()
window.exitonclick()

(4)用python绘制爱心树

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

import turtle
import randomdef love(x, y):         # 在(x,y)处画爱心lalalalv = turtle.Turtle()lv.hideturtle()lv.up()lv.goto(x, y)       # 定位到(x,y)def curvemove():    # 画圆弧for i in range(20):lv.right(10)lv.forward(2)lv.color('red', 'pink')lv.speed(10000000)lv.pensize(1)# 开始画爱心lalalalv.down()lv.begin_fill()lv.left(140)lv.forward(22)curvemove()lv.left(120)curvemove()lv.forward(22)lv.write("YZ", font=("Arial", 12, "normal"), align="center")  # 写上表白的人的名字lv.left(140)  # 画完复位lv.end_fill()def tree(branchLen, t):if branchLen > 5:       # 剩余树枝太少要结束递归if branchLen < 20:  # 如果树枝剩余长度较短则变绿t.color("green")t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))t.down()t.forward(branchLen)love(t.xcor(), t.ycor())  # 传输现在turtle的坐标t.up()t.backward(branchLen)t.color("brown")returnt.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))t.down()t.forward(branchLen)# 以下递归ang = random.uniform(15, 45)t.right(ang)tree(branchLen - random.uniform(12, 16), t)  # 随机决定减小长度t.left(2 * ang)tree(branchLen - random.uniform(12, 16), t)  # 随机决定减小长度t.right(ang)t.up()t.backward(branchLen)myWin = turtle.Screen()
t = turtle.Turtle()
t.hideturtle()
t.speed(1000)
t.left(90)
t.up()
t.backward(200)
t.down()
t.color("brown")
t.pensize(32)
t.forward(60)
tree(100, t)
myWin.exitonclick()

(5)用matplotlib绘制一颗2D的红心

import numpy as np

import matplotlib.pyplot as plt

x = np.linspace(-np.pi/2, np.pi/2, 1000)

y1 = np.power(np.cos(x),0.5) * np.cos(200*x) + np.power(np.absolute(x),0.5) - 0.7

y2 = np.power(4-np.power(x, 2), 0.01)

plt.plot(x, y1*y2, c='r')

plt.show()

原:https://blog.csdn.net/xufive/article/details/126141038

import matplotlib.pyplot as plt

import numpy as np

import math

x = np.linspace(-2,2,500)

y=lambda x:np.power((x**2),(1/3))+0.99*np.sqrt(3.3-np.power(x,2))*np.sin(9.9*math.pi*x)

plt.plot(x,y(x))

plt.axis([-3,3,-2,3])

plt.show()

原 :https://zhuanlan.zhihu.com/p/271674164

(6)三维爱心

转载地址:https://blog.csdn.net/yunyun889901/article/details/117785181

#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as npdef heart_3d(x,y,z):return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3def plot_implicit(fn, bbox=(-1.5, 1.5)):''' create a plot of an implicit functionfn ...implicit function (plot where fn==0)bbox ..the x,y,and z limits of plotted interval'''xmin, xmax, ymin, ymax, zmin, zmax = bbox*3fig = plt.figure()ax = fig.add_subplot(111, projection='3d')A = np.linspace(xmin, xmax, 100) # resolution of the contourB = np.linspace(xmin, xmax, 40) # number of slicesA1, A2 = np.meshgrid(A, A) # grid on which the contour is plottedfor z in B: # plot contours in the XY planeX, Y = A1, A2Z = fn(X, Y, z)cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))# [z] defines the only level to plot# for this contour for this value of zfor y in B: # plot contours in the XZ planeX, Z = A1, A2Y = fn(X, y, Z)cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))for x in B: # plot contours in the YZ planeY, Z = A1, A2X = fn(x, Y, Z)cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))# must set plot limits because the contour will likely extend# way beyond the displayed level. Otherwise matplotlib extends the plot limits# to encompass all values in the contour.ax.set_zlim3d(zmin, zmax)ax.set_xlim3d(xmin, xmax)ax.set_ylim3d(ymin, ymax)plt.show()if __name__ == '__main__':plot_implicit(heart_3d)#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as npdef heart_3d(x,y,z):return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3def plot_implicit(fn, bbox=(-1.5, 1.5)):''' create a plot of an implicit functionfn ...implicit function (plot where fn==0)bbox ..the x,y,and z limits of plotted interval'''xmin, xmax, ymin, ymax, zmin, zmax = bbox*3fig = plt.figure()ax = fig.add_subplot(111, projection='3d')A = np.linspace(xmin, xmax, 100) # resolution of the contourB = np.linspace(xmin, xmax, 40) # number of slicesA1, A2 = np.meshgrid(A, A) # grid on which the contour is plottedfor z in B: # plot contours in the XY planeX, Y = A1, A2Z = fn(X, Y, z)cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))# [z] defines the only level to plot# for this contour for this value of zfor y in B: # plot contours in the XZ planeX, Z = A1, A2Y = fn(X, y, Z)cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))for x in B: # plot contours in the YZ planeY, Z = A1, A2X = fn(x, Y, Z)cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))# must set plot limits because the contour will likely extend# way beyond the displayed level. Otherwise matplotlib extends the plot limits# to encompass all values in the contour.ax.set_zlim3d(zmin, zmax)ax.set_xlim3d(xmin, xmax)ax.set_ylim3d(ymin, ymax)plt.show()if __name__ == '__main__':plot_implicit(heart_3d)

(7)Matlab 3D心形代码

原:https://blog.csdn.net/weixin_48117689/article/details/124082260

clear;  clc;  close all; f = @(x, y, z)(x.^2 + 2.25*y.^2 + z.^2 - 1).^3 -  ...x.^2.* z.^3 - 0.1125*y.^2.*z.^3;g = @(x, y, z)(sqrt(x.^2+y.^2)-2.5).^2 + z.^2 - 0.4^2;t = linspace(-5, 5);[x1, y1, z1] = meshgrid(t);[x2, y2, z2] = meshgrid(t);val1 = f(x1, y1, z1);val2 = g(x2, y2, z2);[p1, v1] = isosurface(x1, y1, z1, val1, 0);[p2, v2] = isosurface(x2, y2, z2, val2, 0);figure()subplot(1, 1, 1)h = patch('faces',p1,'vertices',v1,'facevertexcdata',jet(size(v1,1)),...'facecolor','w','edgecolor','flat'); hold on;patch('faces',p2,'vertices',v2,'facevertexcdata',jet(size(v2,1)),...'facecolor','w','edgecolor','flat');grid on; axis equal; axis([-3,3,-3,3,-1.5,1.5]); view(3)title()warning('off');T = suptitle("$I\ Love\ U\ !$"); set(T,'Interpreter','latex','FontSize',24)pic_num = 1;for i = 1:20v1 = 0.98 * v1;set(h, 'vertices', v1); drawnow;F = getframe(gcf);I = frame2im(F);[I,map]=rgb2ind(I,256);if pic_num == 1imwrite(I,map,'BeatingHeart.gif','gif','Loopcount',inf,'DelayTime',0.05);elseimwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05);endpic_num = pic_num + 1;endfor i = 1:20v1 = v1 / 0.98;set(h, 'vertices', v1); drawnow;F = getframe(gcf);I = frame2im(F);[I,map] = rgb2ind(I,256);imwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05);pic_num = pic_num + 1;end

(8)双心(java)

https://zhuanlan.zhihu.com/p/511112228

import javax.swing.*;
import java.awt.*;
​
import static java.lang.Math.*;
​
public class DemoTest extends JFrame {private static final long serialVersionUID = -1284128891908775645L;
​// 定义加载窗口大小
​public static final int GAME_WIDTH = 500;
​public static final int GAME_HEIGHT = 500;// 获取屏幕窗口大小public static final int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
​public static final int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;
​public DemoTest() {
​// 设置窗口标题this.setTitle("心形曲线");// 设置窗口初始位置this.setLocation((WIDTH - GAME_WIDTH) / 2, (HEIGHT - GAME_HEIGHT) / 2);// 设置窗口大小this.setSize(GAME_WIDTH, GAME_HEIGHT);// 设置背景色this.setBackground(Color.BLACK);// 设置窗口关闭方式this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置窗口显示this.setVisible(true);}
​@Overridepublic void paint(Graphics g) {double x, y, r;Image OffScreen = createImage(GAME_WIDTH, GAME_HEIGHT);Graphics drawOffScreen = OffScreen.getGraphics();for (int i = 0; i < 90; i++) {for (int j = 0; j < 90; j++) {r = Math.PI / 45 * i * (1 - Math.sin(Math.PI / 45 * j)) * 18;x = r * Math.cos(Math.PI / 45 * j) * Math.sin(Math.PI / 45 * i) + GAME_WIDTH / 2;y = -r * Math.sin(Math.PI / 45 * j) + GAME_HEIGHT / 4;//设置画笔颜色drawOffScreen.setColor(Color.PINK);// 绘制椭圆drawOffScreen.fillOval((int) x, (int) y, 2, 2);}// 生成图片g.drawImage(OffScreen, 0, 0, this);}}
​public static void main(String[] args) {DemoTest demo = new DemoTest();demo.setVisible(true);}
​
}

(9)C语言动态爱心代码

https://blog.csdn.net/m0_67388084/article/details/127728441
#include <stdio.h>
#include <math.h>
#include <windows.h>
#include <tchar.h>float f(float x, float y, float z) {float a = x * x + 9.0f / 4.0f * y * y + z * z - 1;return a * a * a - x * x * z * z * z - 9.0f / 80.0f * y * y * z * z * z;
}float h(float x, float z) {for (float y = 1.0f; y >= 0.0f; y -= 0.001f)if (f(x, y, z) <= 0.0f)return y;return 0.0f;
}int main() {SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0xc);//SetConsoleTextAttribute()是Windows系统中一个可以设置控制台窗口字体颜色和背景色的计算机函数HANDLE o = GetStdHandle(STD_OUTPUT_HANDLE);// GetStdHandle()检索指定标准设备的句柄(标准输入、标准输出或标准错误)_TCHAR buffer[25][80] = { _T(' ') };_TCHAR ramp[] = _T("vvvvvvvv");int count = 0;int count1 = 0;for (float t = 0.0f;; t += 0.1f) {int sy = 0;float s = sinf(t);float a = s * s * s * s * 0.2f;for (float z = 1.3f; z > -1.2f; z -= 0.1f) {_TCHAR *p = &buffer[sy++][0];float tz = z * (1.2f - a);for (float x = -1.5f; x < 1.5f; x += 0.05f) {float tx = x * (1.2f + a);float v = f(tx, 0.0f, tz);if (v <= 0.0f) {float y0 = h(tx, tz);float ny = 0.01f;float nx = h(tx + ny, tz) - y0;float nz = h(tx, tz + ny) - y0;float nd = 1.0f / sqrtf(nx * nx + ny * ny + nz * nz);float d = (nx + ny - nz) * nd * 0.5f + 0.5f;*p++ = ramp[(int)(d * 5.0f)];} else*p++ = ' ';}}for (sy = 0; sy < 25; sy++) {COORD coord = { 0, sy };SetConsoleCursorPosition(o, coord);//作用是设置控制台(cmd)光标位置WriteConsole(o, buffer[sy], 79, NULL, 0);//从当前光标位置开始,将字符串写入控制台屏幕缓冲区}if (count <= 22) {printf("I Love You") ;//表白内容printf("            To CSDN");// 被表白者的名字count++;} else {printf("You Are My Best Lover.\n");count++;if (count >= 44) {count = 0;}}Sleep(36);//Sleep函数:执行挂起一段时间,也就是等待一段时间在继续执行}
}

(10)、Python《点燃我温暖你》李峋爱心代码

转载地址:【双十一特辑】爱心代码(程序员的浪漫)-李峋_天寒雨落的博客-CSDN博客
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_ratioy *= shrink_ratio# 移到画布中央x += CANVAS_CENTER_Xy += CANVAS_CENTER_Yreturn 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 - dydef 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 - dydef 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 = 1000self.generate_frame = generate_framefor 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))@staticmethoddef 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 - dydef 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_pointsdef 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()  # 一个Tkcanvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)canvas.pack()heart = Heart()  # 心draw(root, canvas, heart)  # 开始画画~root.mainloop()

三、用python、java字符画绘制爱心

(1)一行代码画爱心

print('\n'.join([''.join([('Love'[(x-y)%len('Love')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ') for x in range(-30,30)]) for y in range(15,-15,-1)]))

a = [
        ''.join(
            [
                (
                    'Love'[(x-y)%len('Love')]
                    if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' '
                )
                for x in range(-30,30)
            ]
        )
        for y in range(15,-15,-1)
    ]

print('\n'.join(a))

(2)用字符输出 I 爱 U (2种形式)

import time
y = 2.5
while y>=-1.6:x = -3.0while x<=4.0:if (x*x+y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):print(' ',end="")else:print('*',end="")x += 0.1print()time.sleep(0.25)y -= 0.2

参考:https://blog.csdn.net/qq_55342245/article/details/120904578

import time
y = 2.5
while y>=-1.6:x = -3.0while x<=4.0:if (x*x+y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):print('*',end="")else:print(' ',end="")x += 0.1print()time.sleep(0.25)y -= 0.2

(3)输出五个爱心,由Dear I love you forever! 五个单词填充而成

转载地址:https://blog.csdn.net/qq_55342245/article/details/120904578

import time
sentence = "Dear, I love you forever!"
for char in sentence.split():allChar = []for y in range(12, -12, -1):lst = []lst_con = ''for x in range(-30, 30):formula = ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3if formula <= 0:lst_con += char[(x) % len(char)]else:lst_con += ' 'lst.append(lst_con)allChar += lstprint('\n'.join(allChar))time.sleep(1)

(4).java 实现 ❤

public  static  void heart1(){

float x,y,a;

for(y=1.3f;y>-1.1f;y-=0.06f){   //这里的参数皆可以调,条件就是看着顺眼

for(x=-1.2f;x<=1.2f;x+=0.025f){

a=x*x+y*y-1;

System.out.print(a*a*a-x*x*y*y*y<=0.0f?' ':'$');

}

System.out.println();

}

}

再来一个心中有无数爱的:

public static  void heart2(){

double x,y,a;

char s[]=new char[]{'I',' ','l','o','v','e',' ','y','o','u','!'};

int index=0;

for(y=1.3f;y>-1.1f;y-=0.06f){

index=0;

for(x=-1.1f;x<=1.1f;x+=0.025f){

double result=x*x+pow((5.0*y/4.0-sqrt(abs(x))),2);

if(result<=1){

System.out.print((s[index]));

index=(index+1)%11;

}

else{

System.out.print(' ');

}

}

System.out.println(" ");

}

}

原:https://zhuanlan.zhihu.com/p/511112228

四、绘制玫瑰花

(1)、6种python玫瑰花绘图源码(立体多层玫瑰、红玫瑰)

(1)立体多层玫瑰 (2)红玫瑰 (3)红玫瑰

(4)红玫瑰 (5)红玫瑰 (6)红玫瑰

篇幅太长,请点击查看: 立体多层玫瑰绘图源码__玫瑰花python 绘图源码集锦

(2)前端canvas玫瑰花

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<style>.flower {margin-left: 32%;margin-top: 9%;}
</style><body><canvas id="c" class="flower"></canvas>
</body></html>
<script>var b = document.body;var c = document.getElementsByTagName('canvas')[0];var a = c.getContext('2d');document.body.clientWidth;with (m = Math) C = cos, S = sin, P = pow, R = random; c.width = c.height = f = 600; h = -250; function p(a, b, c) { if (c > 60) return [S(a * 7) * (13 + 5 / (.2 + P(b * 4, 4))) - S(b) * 50, b * f + 50, 625 + C(a * 7) * (13 + 5 / (.2 + P(b * 4, 4))) + b * 400, a * 1 - b / 2, a]; A = a * 2 - 1; B = b * 2 - 1; if (A * A + B * B < 1) { if (c > 37) { n = (j = c & 1) ? 6 : 4; o = .5 / (a + .01) + C(b * 125) * 3 - a * 300; w = b * h; return [o * C(n) + w * S(n) + j * 610 - 390, o * S(n) - w * C(n) + 550 - j * 350, 1180 + C(B + A) * 99 - j * 300, .4 - a * .1 + P(1 - B * B, -h * 6) * .15 - a * b * .4 + C(a + b) / 5 + P(C((o * (a + 1) + (B > 0 ? w : -w)) / 25), 30) * .1 * (1 - B * B), o / 1e3 + .7 - o * w * 3e-6] } if (c > 32) { c = c * 1.16 - .15; o = a * 45 - 20; w = b * b * h; z = o * S(c) + w * C(c) + 620; return [o * C(c) - w * S(c), 28 + C(B * .5) * 99 - b * b * b * 60 - z / 2 - h, z, (b * b * .3 + P((1 - (A * A)), 7) * .15 + .3) * b, b * .7] } o = A * (2 - b) * (80 - c * 2); w = 99 - C(A) * 120 - C(b) * (-h - c * 4.9) + C(P(1 - b, 7)) * 50 + c * 2; z = o * S(c) + w * C(c) + 700; return [o * C(c) - w * S(c), B * 99 - C(P(b, 7)) * 50 - c / 3 - z / 1.35 + 450, z, (1 - b / 1.2) * .9 + a * .1, P((1 - b), 20) / 4 + .05] } } setInterval('for(i=0;i<1e4;i++)if(s=p(R(),R(),i%46/.74)){z=s[2];x=~~(s[0]*f/z-h);y=~~(s[1]*f/z-h);if(!m[q=y*f+x]|m[q]>z)m[q]=z,a.fillStyle="rgb("+~(s[3]*h)+","+~(s[4]*h)+","+~(s[3]*s[3]*-80)+")",a.fillRect(x,y,1,1)}', 0)
</script>

五、前端特效爱心

(1)前端 CSS "I Love You "爱心效果

<html>
<head></head>
<body><div class="wrapper"><input type="checkbox" id="ck1"><label for="ck1">I</label><input type="checkbox" id="ck2"><label for="ck2">love</label><input type="checkbox" id="ck3"><label for="ck3">you</label></div><span>点击每个单词查看效果</span><style>html {display: table;width: 100%; height: 100%;table-layout: fixed;}body {display: table-cell;width: 100%; height: 100%;vertical-align: middle;font-family: 'Shadows Into Light';color: #111;}.wrapper {width: 500px; height: 500px;position: relative;margin: 0 auto;}input[type="checkbox"] {display: none;}input[type="checkbox"] + label {width: 100px; height: 100px;line-height: 100px;display: inline-block;position: absolute;text-align: center;font-size: 100px;transition: all 1s ease;}label {text-shadow: 8px 8px 30px rgba(0,0,0,0.5);}label:hover {color: #c32a2a;cursor: pointer;}#ck1 + label,#ck2 + label {border-radius: 50px;top: 0;}#ck1:checked + label,#ck2:checked + label,#ck3:checked + label {background: #c32a2a;font-size: 0;transition: all 1s ease;}#ck1:checked + label,#ck2:checked + label {width: 300px; height: 300px;border-radius: 150px;line-height: 300px;}#ck1 + label {left: 0;}#ck2 + label {right: 0;}#ck3 + label {bottom: 0; left: 50%;margin: 0 -50px;}#ck3:checked + label {width: 275px; height: 275px;bottom: 96px; left: 162px;transform: rotate(45deg);line-height: 27px;}span {display: inline-block;text-align: center;position: absolute;bottom: 10px; left: 50%;margin-left: -100px;width: 200px;font-size: 24px;color: #999;}</style>
</body>
</html>

(2)各国语言“爱”字组成爱心效果

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://cdn.staticfile.org/d3/4.13.0/d3.min.js"></script><style>body {margin: 0;height: 100vh;display: flex;align-items: center;justify-content: center;background-color: black;overflow: hidden;
}.love {width: 450px;height: 450px;position: relative;
}.love span {position: absolute;left: 0;color: goldenrod;font-size: 20px;font-family: sans-serif;text-shadow: 0 0 1em white;animation: x-move 10s ease-in-out infinite alternate,y-move 20s linear infinite;animation-delay: calc(20s / var(--particles) * var(--n) * -1);user-select: none;
}.love span:first-child {color: orangered;font-size: 3em;text-shadow: 0 0 0.1em black,0 0 1em white;z-index: 1;
}@keyframes x-move {to {left: 450px;}
}@keyframes y-move {0% { transform: translateY(180px); }10% { transform: translateY(45px); }15% { transform: translateY(5px); }18% { transform: translateY(0); }20% { transform: translateY(5px); }22% { transform: translateY(35px); }24% { transform: translateY(65px); }25% { transform: translateY(110px); }26% { transform: translateY(65px); }28% { transform: translateY(35px); }30% { transform: translateY(5px); }32% { transform: translateY(0); }35% { transform: translateY(5px); }40% { transform: translateY(45px); }50% { transform: translateY(180px); }71% { transform: translateY(430px); }72.5% { transform: translateY(440px); }75% { transform: translateY(450px); }77.5% { transform: translateY(440px); }79% { transform: translateY(430px); }100% { transform: translateY(180px); }
}</style>
</head><body><div class="love"></div>
</body></html>
<script>const words = ['爱', 'Love', 'Amour', 'Liebe', 'Amore','Amor', 'Любовь', 'الحب', 'प्यार', 'Cinta','Αγάπη', '사랑', 'Liefde', 'Dashuri', 'Каханне','Ljubav', 'Láska', 'Armastus', 'Mahal', 'אהבה', 'Szerelem', 'Grá', 'Mīlestība', 'Meilė', 'Любов', 'Љубовта', 'Cinta', 'عشق', 'Dragoste', 'Láska', 'Renmen', 'ፍቅር', 'munaña', 'Sevgi', 'Љубав', 'karout', 'amà', 'amôr', 'kærleiki', 'mborayhu', 'Upendo', 'sòòyayyàà', 'ljubav', 'Սեր', 'сүю', 'сүйүү', 'tia', 'aroha', 'KHAIR', 'प्रेम', 'kjærlighet', 'munay', 'jecel', 'Kärlek', 'soymek', 'Mahal', 'ярату', 'محبت', 'sopp', 'uthando', 'ความรัก', 'Aşk', 'Tình yêu', 'ליבע'];d3.select('.love').style('--particles', words.length).selectAll('span').data(words).enter().append('span').style('--n', (d, i) => i + 1).text((d) => d);
</script>

(3)上升爱心效果

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><canvas id="cavs"></canvas>
</body>
</html>
<script>var canvas = document.getElementById("cavs");const WIDTH = window.innerWidth;const HEIGHT = window.innerHeight;canvas.setAttribute("width", WIDTH);canvas.setAttribute("height", HEIGHT);var context = canvas.getContext("2d");var start ={loves: [],DURATION: 30,begin: function () {this.createLove();},createLove: function () {for (var i = 0; i < WIDTH / 59; i++) {var love = new Love();this.loves.push(love);}setInterval(this.drawLove.bind(this), this.DURATION);},drawLove: function () {context.clearRect(0, 0, WIDTH, HEIGHT);for (var key in this.loves) {this.loves[key].draw();}}}function Love() {var me = this;function rand() {me.attr.scale = (Math.random() * 0.8 + 0.3) * WIDTH / 521;me.attr.x = Math.floor(Math.random() * WIDTH - 40);me.attr.y = Math.floor(HEIGHT - Math.random() * 200);me.attr.ColR = Math.floor(Math.random() * 255);me.attr.ColG = Math.floor(Math.random() * 255);me.attr.ColB = Math.floor(Math.random() * 255);me.attr.alpha = Math.random() * 0.2 + 0.8;me.attr.vector = Math.random() * 5 + 0.4;}(function () { me.attr = {}; rand(); }());me.draw = function () {if (me.attr.alpha < 0.01) rand();x = me.attr.x;y = me.attr.y;scale = 4 * me.attr.scale;context.beginPath();context.bezierCurveTo(x + 2.5 * scale, y + 2.5 * scale, x + 2.0 * scale, y, x, y);context.bezierCurveTo(x - 3.0 * scale, y, x - 3.0 * scale, y + 3.5 * scale, x - 3.0 * scale, y + 3.5 * scale);context.bezierCurveTo(x - 3.0 * scale, y + 5.5 * scale, x - 1.0 * scale, y + 7.7 * scale, x + 2.5 * scale, y + 9.5 * scale);context.bezierCurveTo(x + 6.0 * scale, y + 7.7 * scale, x + 8.0 * scale, y + 5.5 * scale, x + 8.0 * scale, y + 3.5 * scale);context.bezierCurveTo(x + 8.0 * scale, y + 3.5 * scale, x + 8.0 * scale, y, x + 5.0 * scale, y);context.bezierCurveTo(x + 3.5 * scale, y, x + 2.5 * scale, y + 2.5 * scale, x + 2.5 * scale, y + 2.5 * scale);context.fillStyle = "rgba(" + me.attr.ColR + "," + me.attr.ColG + "," + me.attr.ColB + "," + me.attr.alpha + ")";context.fill();context.lineWidth = 0.5;context.stroke();me.attr.y -= me.attr.vector;me.attr.alpha -= (me.attr.vector / 2.9 * 3.5 / HEIGHT);}}window.onload = function () {start.begin();}
</script>

(4)变幻爱心

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><canvas id="c"></canvas>
</body>
</html>
<script>var b = document.body,c = document.getElementsByTagName('canvas')[0],a = c.getContext('2d');document.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218// ### Pixel Love - a js1k 2012 entry by @aaronsnoswell
// This demo is on [github](https://github.com/aaronsnoswell/js1k-2012-love)// You can also browse the annotated source code at [http://aaronsnoswell.github.com/js1k-2012-love/docs/](http://aaronsnoswell.github.com/js1k-2012-love/docs/)// Define some variables:var h = "❤",      // A heartg = 5,        // The granularity - determines the size of each 'pixel'l = 10,       // The threshold / limit, used for determining where to place pixelsoutline = [], // Arrays of locations for the outline and fill pixlesfill = [],sx = 100,     // Where to draw the heartsy = 450,box = [999, 999, 0, 0]; // The bounding box of the heart (computed later)// Set the canvas size
c.width = 500;
c.height = 800;// A utility function, used for looping over an x and y variable
var loopxy = function(w, h, step, callback) {for(var x=0; x<w; x+=step) {for(var y=0; y<h; y+=step) {callback(x, y, step);}}
}// Shortcut method for clearing the canvas
a.clear = function() {a.clearRect(0, 0, c.width, c.height);
}// Normalise browser font rendering in the canvas.
// See [https://twitter.com/#!/aaronsnoswell/status/165642474109419520](https://twitter.com/#!/aaronsnoswell/status/165642474109419520)
a.textBaseline = "bottom";
a.font="300pt arial";
a.lineWidth = g*2;// Draw a filled heart on the canvas
a.fillText(h, sx, sy);// Loop over the entire canvas and wherever there are filled pixels,
// store that location in the fill array
var d = a.getImageData(0, 0, c.width, c.height)
loopxy(d.width, d.height, g, function(x, y) {if(d.data[(x + y*d.width)*4+3] >= l) fill.push([x, y]);
});// Clear the screen
a.clear();// Draw an outline of a heart on the canvas
a.strokeText(h, sx, sy);// Loop over the entire canvas once again. Wherever there are filled
// pixels, store that location in the outline array
var d = a.getImageData(0, 0, c.width, c.height)
loopxy(d.width, d.height, g, function(x, y) {if(d.data[(x + y*d.width)*4+3] >= l) {outline.push([x, y]);// Compute the bounding box of the heartif(x<box[0]) box[0] = x;if(x>box[2]) box[2] = x;if(y<box[1]) box[1] = y;if(y>box[3]) box[3] = y;}
});// Find the middle x and y locations of the heart
box.push((box[0]+box[2])/2);
box.push((box[1]+box[3])/2);// Store the current time as ms since epoch
var t0 = new Date().getTime();// Use a recursive named function + setTimeout to ensure each frame has
// time to finish before the next one is drawn
(function render() {window.setTimeout(function() {// Time delta and elapsed timevar d = new Date().getTime()-t0;t0 += d;// Clear the screena.clear();// Draw the red hearta.fillStyle = "#f00";loopxy(fill.length, 1, 1, function(i) {var x = fill[i][0],y = fill[i][1];// Offset each pixel by a sinusoidal, time based ammounta.fillRect(x-g/2+Math.sin(t0/500+y/80)*(x-box[4])+10, y-g/2+10, g, g);})// Draw the outline using the same logic as abovea.fillStyle = "#000";loopxy(outline.length, 1, 1, function(i) {var x = outline[i][0],y = outline[i][1];a.fillRect(x-g/2+Math.sin(t0/500+y/80)*(x-box[4])+10, y-g/2+10, g, g);})// Loop at 30fpsrender();}, 1/30);
})();
</script>

(5)红心下落动画

原:74行代码实现浪漫的红心下落的动画效果_汪子熙的博客-CSDN博客
<html>
<canvas></canvas>
<script>var c = document.getElementsByTagName('canvas')[0];var b = document.body;var a = c.getContext('2d');function d(b, c, d, e) {a.fillStyle = b;a.beginPath();a.arc(c, d, e, 0, 2 * m.PI, !0);a.fill();a.fillRect(c, d, 1, 1)}m = Math;r = m.random;g = Date;l = +(new g);e = document;q = e.createElement("canvas");w = e.createElement("canvas");o = {};h = 100;H = 200;v = window;t = c.width = v.innerWidth;u = c.height = v.innerHeight - 5;b.setAttribute("style", "margin:0;background:#000");k = a;q.width = q.height = h;w.width = 1e3;w.height = H;for (j = 0; ++j < H; ) {for (i = 0; 1e3 > ++i; )a = q.getContext("2d"),z = .5 - i / h,f = j / h - .5 + .4 * m.sqrt(m.abs(z)),f = z * z + 2 * f * f,.23 > f && d(.16 < f ? "#F00" : "#F88", i, j, 0),a = w.getContext("2d"),d(j > 5e-4 * i * i - .3 * i + h ? "#343" : j > 4e-4 * i * i - .9 * i + 500 ? "#232" : "#000", i, j, 0);o[j] = {x: r() * t,y: -h - r() * u,b: 51 - j / 4,a: 25 + .4 * j};o[H + j] = {x: r() * t,y: r() * u - H,a: 3 * r() + 1,c: j}}a = k;v.setInterval(function() {n = +(new g);a.clearRect(0, 0, t, u);d("#FFA", H, 250, 150);d("#000", 270, 320, h);a.drawImage(w, 0, u - H, t, H);for (i = 0; ++i < H; )f = (n - l) / h,s = o[H + i],d("#FFA", s.x, s.y, m.floor(m.max(s.a + m.sin(s.c++ / 10) - .5, 1))),z = o[i],a.drawImage(q, z.x += -.1 / (z.b / h) * f, z.y += (5 - z.b / 10) * f, z.a, z.a),z.y > u && (z.y = -h),z.x < -H && (z.x = t);l = n}, 60)//L<3
</script></html>

(6)《点燃我温暖你》中李峋的爱心代码

转载地址:HTML爱心代码 | 一起体验理工男的极致浪漫(电视剧男主同款)_陈橘又青的博客-CSDN博客
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE> New Document </TITLE><META NAME="Generator" CONTENT="EditPlus"><META NAME="Author" CONTENT=""><META NAME="Keywords" CONTENT=""><META NAME="Description" CONTENT=""><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 particlesduration:   2, // particle duration in secvelocity: 100, // particle velocity in pixels/seceffect: -0.75, // play with this for a nice effectsize:      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 poolparticles = 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 queuefirstFree++;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 particlesif (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 particleswhile (particles[firstActive].age >= duration && firstActive != firstFree) {firstActive++;if (firstActive == particles.length) firstActive = 0;}};ParticlePool.prototype.draw = function(context, image) {// draw active particlesif (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/sectime;// get point on heart with -PI <= t <= PIfunction 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 canvasvar 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 pathfunction 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 pathcontext.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 fillcontext.fillStyle = '#ea80b0';context.fill();// create the imagevar image = new Image();image.src = canvas.toDataURL();return image;})();// render that thing!function render() {// next animation framerequestAnimationFrame(render);// update timevar newTime   = new Date().getTime() / 1000,deltaTime = newTime - (time || newTime);time = newTime;// clear canvascontext.clearRect(0, 0, canvas.width, canvas.height);// create new particlesvar 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 particlesparticles.update(deltaTime);particles.draw(context, image);}// handle (re-)sizing of the canvasfunction onResize() {canvas.width  = canvas.clientWidth;canvas.height = canvas.clientHeight;}window.onresize = onResize;// delay rendering bootstrapsetTimeout(function() {onResize();render();}, 10);
})(document.getElementById('pinkboard'));</script></BODY>
</HTML>

六、特色推荐

作者:@_猿来如此 作者:带中小学生玩转Python
https://blog.csdn.net/m0_63057469/article/details/126091105 https://blog.csdn.net/m0_48190198/article/details/123235264
用Pygame制作一场漂亮的流星雨 爱心字符云
https://blog.csdn.net/wangzirui32/article/details/115825539 https://blog.csdn.net/weixin_55822277/article/details/121370628

 推荐阅读:

25

2023春节祝福系列第一弹(上)(放飞祈福孔明灯,祝福大家身体健康)(附完整源代码及资源免费下载)
24

HTML+CSS+svg绘制精美彩色闪灯圣诞树,HTML+CSS+Js实时新年时间倒数倒计时(附源代码)

23

​草莓熊python绘图(春节版,圣诞倒数雪花版)附源代码

22

【程序人生】卡塔尔世界杯元素python海龟绘图(附源代码),世界杯主题前端特效5个(附源码)

21

​​

python爱心源代码集锦
20

​​

巴斯光年python turtle绘图__附源代码
19

​​​

Three.js实例详解___旋转的精灵女孩(附完整代码和资源)
18

​​​​

​草莓熊python turtle绘图(玫瑰花版)附源代码

17

​​​​

立体多层玫瑰绘图源码__玫瑰花python 绘图源码集锦

16

​​​​

皮卡丘python turtle海龟绘图(电力球版)附源代码

15

​​​​

【CSDN云IDE】个人使用体验和建议(含超详细操作教程)(python、webGL方向)

14

​​​​

草莓熊python turtle绘图(风车版)附源代码

13

​​​​

用代码过中秋,python海龟月饼你要不要尝一口?

12

​​​​

《 Python List 列表全实例详解系列》__系列总目录

11

​​​​

用代码写出浪漫__合集(python、matplotlib、Matlab、java绘制爱心、玫瑰花、前端特效玫瑰、爱心)

10

​​​​

Python函数方法实例详解全集(更新中...)

9

​​​​

matplotlib 自带绘图样式效果展示速查(28种,全)

8

​​​​

手机屏幕坏了____怎么把里面的资料导出(18种方法)

7

​​​​

2023年1月多家权威机构____编程语言排行榜__薪酬状况

6

​​​​

Python中Print()函数的用法___实例详解(全,例多)

5

​​​​

色彩颜色对照表(300种颜色)(16进制、RGB、CMYK、HSV、中英文名)

4

​​​​

Node.js (v19.1.0npm 8.19.3) vue.js安装配置教程(超详细)

3

​​​​

Tomcat 启动闪退问题解决集(八大类详细)

2

​​​​

Tomcat端口配置(详细)

1

​​​​

Tomcat10 安装(Windows环境)(详细)sss

用代码写出浪漫__合集(python、matplotlib、Matlab、java绘制爱心、玫瑰花、前端特效玫瑰、爱心)相关推荐

  1. python手机小游戏刷分器_如何用5行Python代码写出刷分游戏脚本!Python真牛!

    几天前, 我母上大人在我们家群里发了一条消息 一看这文案, 就知道又是一个骗流量的小游戏, 一看就让人没什么兴趣... 但是出于对我母上大人的尊(hào)重(qí)我还是点进来看了一下 游戏链接: 游 ...

  2. 关于下拉刷新你是否真的非常理解还是只会搬砖?附 Android 实例子源代码文件下载地址380个合集...

    1,推荐几篇非常有用的博文 原创写的真的非常好 主要讲解原理,整体布局三部分组成以及设置padding等等作用, 下拉的具体实现 滑动到底部具体加载以及判断手势事件,再次推荐作者的 详细讲解 建议先看 ...

  3. 人群计数最全代码、数据、论文合集

    2021.11.19更新: 人群计数 /Crowd Counting Rethinking Counting and Localization in Crowds:A Purely Point-Bas ...

  4. mysql扩展中如何处理结果集_请写出PHP处理结果集的5个函数(使用mysql扩展)_学小易找答案...

    [单选题]在MySQL中,选择数据库的命令是( ) [单选题]开启mysqli扩展的配置语句是( ). [单选题]19世纪美国杰出的浪漫主义小说家麦尔维尔的代表作是 [单选题]卤素灯检漏时,发现管子大 ...

  5. Python编曲实践(八):我,乔鲁诺·乔巴那,能用两百行代码写出JOJO黄金之风里我自己的出场曲!

    前言 前些天笔者写的文章 Python编曲实践(七):整整一百行Python代码写出黑人抬棺梗曲<Astronomia>的旋律 受到了大家的许多支持和好评,本篇文章挑战更复杂.更有挑战性, ...

  6. 如何用PYTHON代码写出音乐

    如何用PYTHON代码写出音乐 什么是MIDI 博主本人虽然五音不全,而且唱歌还很难听,但是还是非常喜欢听歌的.我一直在做这样的尝试,就是通过人工智能算法实现机器自动的作词和编曲(在这里预告下,通过深 ...

  7. python怎么实现音乐快进_如何用PYTHON代码写出音乐【】

    如何制作MIDI(用于vocaloid 3) 我也是因为V家才来找midi的 如何用PYTHON代码写出音乐 在python-midi,每个乐谱用Pattern对象表示,乐的每个音轨(通常音乐很多轨道 ...

  8. alert不会影响到页面中其他代码执行_JavaScript调试技巧合集——为什么不推荐使用alert调试代码?...

    导读 本文是<JavaScript调试技巧合集>系列分享中的一篇,笔者希望在每篇文章中介绍一个关于JS调试的小知识点,希望你在读完这个系列后,在调试技巧上能够更加运用自如.下面是知识点概览 ...

  9. 电脑蓝屏代码大全及解决办法合集

    代码 含意 0 0x00000000 作业完成. 1 0x00000001 不正确的函数. 2 0x00000002 系统找不到指定的档案. 3 0x00000003 系统找不到指定的路径. 4 0x ...

最新文章

  1. R语言IQR函数计算四分位数范围IQR(Interquartile Range)实战
  2. 小程序无限层级路由方案
  3. Java开发面试问题,牛逼轰轰!
  4. Storm Trident拓扑中的错误处理
  5. 使用Seaborn和Pandas进行数据可视化
  6. 学校计算机协会有哪些部门,大学生计算机协会部门职能划分(7页)-原创力文档...
  7. linux装流量宝,流量宝下载_流量宝官方APP手机最新版本下载安装 - 风云下载
  8. 功率放大器的设计要点
  9. 平面设计之PS(前)
  10. 迅雷调用Potplayer边下边播
  11. qcc302x qcc303x qcc512x TWS earbud通用操作说明 及体验软件
  12. 雷军在联想演讲:全场无言,除了掌声
  13. 聚合查询越来越慢?——详解Elasticsearch的Global Ordinals与High Cardinality
  14. 今日头条python_GitHub - a57571735/headlines_today: 基于Python的爬取今日头条文章及视频...
  15. HTTP协议与www浅谈
  16. 这三款软件让你实现PDF批量转图片
  17. 联想7400pro打印有横黑道
  18. PR模板 复古回忆棱镜光效梦幻内容展示PR视频模板
  19. 再一次获取你的WIFI密码(fluxion附视频)
  20. 巴贝奇——筹划信息时代

热门文章

  1. c语言里的pow函数
  2. Git的Fast Forward和no fast foward合并模式对比
  3. 免费在线工具制作自己的卡通头像
  4. 人工智能发展史-从图灵测试到大数据
  5. Adobe Lightroom2023:完美的数字照片管理和处理软件
  6. 在人工智能高速发展的背景下,如何更好地培养人才?
  7. UI组件库Kendo UI for Vue中文入门指南(二)
  8. 狗狗的年龄的python编程_您狗狗多大了,相当于人的几岁,您知道吗?(狗狗的年龄算法)...
  9. Ionic 样式:bar-positive和bar-assertive
  10. python图像特征提取与匹配_[OpenCV-Python] OpenCV 中图像特征提取与描述 部分 V (二)...