专注app软件定制开发用代码写出浪漫__合集(python、matplotlib、Matlab、java绘制爱心、玫瑰花、前端特效玫瑰、爱心)

活动地址:

专注app软件定制开发用代码写出浪漫合集(爱心、玫瑰花)

     

本文目录:


​一、前言

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

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

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

二、用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爱心绘图的请点击以下链接:

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

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

  1. import turtle
  2. import time
  3. def LittleHeart():
  4. for i in range(200):
  5. turtle.right(1)
  6. turtle.forward(2)
  7. # love = input('请输入表白语句,然后回车,默认为"I Love You":')
  8. # me = input('请输入要表白的人:')
  9. # if love=='':
  10. # # 如果未输入表白语句,则使用默认语句
  11. # love='I Love you'
  12. love='I Love you'
  13. me = '卧槽,这年轻人。'
  14. turtle.setup(width=900,height=600) # 爱心的画布的大小
  15. turtle.color('red','red') # 爱心的颜色及外边笔的颜色
  16. turtle.pensize(5) # 画笔的粗细
  17. turtle.speed(1000000) # 绘制速度
  18. turtle.up() # 画笔向上
  19. turtle.hideturtle()
  20. turtle.goto(0,-180)
  21. turtle.showturtle()
  22. turtle.down()
  23. turtle.speed(5)
  24. turtle.begin_fill()
  25. # 开始填充
  26. turtle.left(140)
  27. turtle.forward(224)
  28. LittleHeart()
  29. turtle.left(120)
  30. LittleHeart()
  31. turtle.forward(224)
  32. turtle.end_fill()
  33. turtle.pensize(5)
  34. turtle.up()
  35. turtle.hideturtle()
  36. turtle.goto(0,0)
  37. turtle.showturtle()
  38. turtle.color('#CD5C5C','pink')
  39. turtle.write(love,font=('gungsuh',30,),align="center")
  40. turtle.up()
  41. turtle.hideturtle()
  42. if me !='':
  43. turtle.color('black', 'pink')
  44. time.sleep(2)
  45. turtle.goto(180,-180)
  46. turtle.showturtle()
  47. turtle.write(me, font=(20,), align="center", move=True)
  48. window=turtle.Screen()
  49. window.exitonclick()


 

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

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

  1. import turtle
  2. import math
  3. turtle.pen()
  4. t=turtle
  5. t.up()
  6. t.goto(0,150)
  7. t.down()
  8. t.color('red')
  9. t.begin_fill()
  10. t.fillcolor('red')
  11. t.speed(1)
  12. t.left(45)
  13. t.forward(150)
  14. t.right(45)
  15. t.forward(100)
  16. t.right(45)
  17. t.forward(100)
  18. t.right(45)
  19. t.forward(100)
  20. t.right(45)
  21. t.forward(250+math.sqrt(2)*100)
  22. t.right (90)
  23. t.speed(2)
  24. t.forward(250+100*math.sqrt(2))
  25. t.right(45)
  26. t.forward(100)
  27. t.right(45)
  28. t.forward(100)
  29. t.right(45)
  30. t.forward(100)
  31. t.right(45)
  32. t.forward(150)
  33. t.end_fill()
  34. t.goto(-10,0)
  35. t.pencolor('white')
  36. # L
  37. t.pensize(10)
  38. t.goto(-50,0)
  39. t.goto(-50,80)
  40. t.up ()
  41. # I
  42. t.goto(-100,0)
  43. t.down()
  44. t.goto(-160,0)
  45. t.goto(-130,0)
  46. t.goto(-130,80)
  47. t.goto(-160,80)
  48. t.goto(-100,80)
  49. t.up()
  50. # O
  51. t.goto(10,25)
  52. t.down()
  53. t.right(45)
  54. t.circle(25,extent=180)
  55. t.goto(60,55)
  56. t.circle(25,extent=180)
  57. t.goto(10,25)
  58. t.up()
  59. t.goto(75,80)
  60. t.down()
  61. t.goto(100,0)
  62. t.goto(125,80)
  63. t.up()
  64. t.goto(180,80)
  65. t.down()
  66. t.goto(140,80)
  67. t.goto(140,0)
  68. t.goto(180,0)
  69. t.up()
  70. t.goto(180,40)
  71. t.down()
  72. t.goto(140,40)
  73. # U
  74. t.up()
  75. t.goto(-40,-30)
  76. t.down()
  77. t.goto(-40,-80)
  78. t.circle(40,extent=180)
  79. t.goto(40,-30)
  80. t.hideturtle()
  81. window=turtle.Screen()
  82. window.exitonclick()

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

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

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

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

  1. # coding: utf-8
  2. import turtle
  3. import time
  4. def LittleHeart():
  5. for i in range(200):
  6. turtle.right(1)
  7. turtle.forward(2)
  8. love=input('请输入表白语句,然后回车,(例如"I Love You"):')
  9. me=input('请输入要表白的人(例如"李思思"):')
  10. if love=='':
  11. love='I Love you'
  12. turtle.setup(width=900,height=600)
  13. turtle.color('red','pink')
  14. turtle.pensize(15)
  15. turtle.speed(1000)
  16. turtle.up()
  17. turtle.hideturtle()
  18. turtle.goto(0,-180)
  19. turtle.showturtle()
  20. turtle.down()
  21. turtle.speed(500)
  22. turtle.begin_fill()
  23. turtle.left(140)
  24. turtle.forward(224)
  25. LittleHeart()
  26. turtle.left(120)
  27. LittleHeart()
  28. turtle.forward(224)
  29. turtle.end_fill()
  30. turtle.pensize(12)
  31. turtle.up()
  32. turtle.hideturtle()
  33. turtle.goto(0,-20)
  34. turtle.showturtle()
  35. turtle.color('#CD5C5C','pink')
  36. turtle.write(love,font=('gungsuh',50,),align="center")
  37. turtle.up()
  38. turtle.hideturtle()
  39. if me !='':
  40. turtle.color('black', 'pink')
  41. time.sleep(1)
  42. turtle.goto(180,-180)
  43. turtle.showturtle()
  44. turtle.write(me, font=(20,25), align="center", move=True)
  45. window=turtle.Screen()
  46. window.exitonclick()

(4)用python绘制爱心树

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

  1. import turtle
  2. import random
  3. def love(x, y): # 在(x,y)处画爱心lalala
  4. lv = turtle.Turtle()
  5. lv.hideturtle()
  6. lv.up()
  7. lv.goto(x, y) # 定位到(x,y)
  8. def curvemove(): # 画圆弧
  9. for i in range(20):
  10. lv.right(10)
  11. lv.forward(2)
  12. lv.color('red', 'pink')
  13. lv.speed(10000000)
  14. lv.pensize(1)
  15. # 开始画爱心lalala
  16. lv.down()
  17. lv.begin_fill()
  18. lv.left(140)
  19. lv.forward(22)
  20. curvemove()
  21. lv.left(120)
  22. curvemove()
  23. lv.forward(22)
  24. lv.write("YZ", font=("Arial", 12, "normal"), align="center") # 写上表白的人的名字
  25. lv.left(140) # 画完复位
  26. lv.end_fill()
  27. def tree(branchLen, t):
  28. if branchLen > 5: # 剩余树枝太少要结束递归
  29. if branchLen < 20: # 如果树枝剩余长度较短则变绿
  30. t.color("green")
  31. t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
  32. t.down()
  33. t.forward(branchLen)
  34. love(t.xcor(), t.ycor()) # 传输现在turtle的坐标
  35. t.up()
  36. t.backward(branchLen)
  37. t.color("brown")
  38. return
  39. t.pensize(random.uniform((branchLen + 5) / 4 - 2, (branchLen + 6) / 4 + 5))
  40. t.down()
  41. t.forward(branchLen)
  42. # 以下递归
  43. ang = random.uniform(15, 45)
  44. t.right(ang)
  45. tree(branchLen - random.uniform(12, 16), t) # 随机决定减小长度
  46. t.left(2 * ang)
  47. tree(branchLen - random.uniform(12, 16), t) # 随机决定减小长度
  48. t.right(ang)
  49. t.up()
  50. t.backward(branchLen)
  51. myWin = turtle.Screen()
  52. t = turtle.Turtle()
  53. t.hideturtle()
  54. t.speed(1000)
  55. t.left(90)
  56. t.up()
  57. t.backward(200)
  58. t.down()
  59. t.color("brown")
  60. t.pensize(32)
  61. t.forward(60)
  62. tree(100, t)
  63. 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

  1. #!/usr/bin/env python3
  2. from mpl_toolkits.mplot3d import Axes3D
  3. from matplotlib import cm
  4. from matplotlib.ticker import LinearLocator, FormatStrFormatter
  5. import matplotlib.pyplot as plt
  6. import numpy as np
  7. def heart_3d(x,y,z):
  8. return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3
  9. def plot_implicit(fn, bbox=(-1.5, 1.5)):
  10. ''' create a plot of an implicit function
  11. fn ...implicit function (plot where fn==0)
  12. bbox ..the x,y,and z limits of plotted interval'''
  13. xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
  14. fig = plt.figure()
  15. ax = fig.add_subplot(111, projection='3d')
  16. A = np.linspace(xmin, xmax, 100) # resolution of the contour
  17. B = np.linspace(xmin, xmax, 40) # number of slices
  18. A1, A2 = np.meshgrid(A, A) # grid on which the contour is plotted
  19. for z in B: # plot contours in the XY plane
  20. X, Y = A1, A2
  21. Z = fn(X, Y, z)
  22. cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
  23. # [z] defines the only level to plot
  24. # for this contour for this value of z
  25. for y in B: # plot contours in the XZ plane
  26. X, Z = A1, A2
  27. Y = fn(X, y, Z)
  28. cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))
  29. for x in B: # plot contours in the YZ plane
  30. Y, Z = A1, A2
  31. X = fn(x, Y, Z)
  32. cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))
  33. # must set plot limits because the contour will likely extend
  34. # way beyond the displayed level. Otherwise matplotlib extends the plot limits
  35. # to encompass all values in the contour.
  36. ax.set_zlim3d(zmin, zmax)
  37. ax.set_xlim3d(xmin, xmax)
  38. ax.set_ylim3d(ymin, ymax)
  39. plt.show()
  40. if __name__ == '__main__':
  41. plot_implicit(heart_3d)
  42. #!/usr/bin/env python3
  43. from mpl_toolkits.mplot3d import Axes3D
  44. from matplotlib import cm
  45. from matplotlib.ticker import LinearLocator, FormatStrFormatter
  46. import matplotlib.pyplot as plt
  47. import numpy as np
  48. def heart_3d(x,y,z):
  49. return (x**2+(9/4)*y**2+z**2-1)**3-x**2*z**3-(9/80)*y**2*z**3
  50. def plot_implicit(fn, bbox=(-1.5, 1.5)):
  51. ''' create a plot of an implicit function
  52. fn ...implicit function (plot where fn==0)
  53. bbox ..the x,y,and z limits of plotted interval'''
  54. xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
  55. fig = plt.figure()
  56. ax = fig.add_subplot(111, projection='3d')
  57. A = np.linspace(xmin, xmax, 100) # resolution of the contour
  58. B = np.linspace(xmin, xmax, 40) # number of slices
  59. A1, A2 = np.meshgrid(A, A) # grid on which the contour is plotted
  60. for z in B: # plot contours in the XY plane
  61. X, Y = A1, A2
  62. Z = fn(X, Y, z)
  63. cset = ax.contour(X, Y, Z+z, [z], zdir='z', colors=('r',))
  64. # [z] defines the only level to plot
  65. # for this contour for this value of z
  66. for y in B: # plot contours in the XZ plane
  67. X, Z = A1, A2
  68. Y = fn(X, y, Z)
  69. cset = ax.contour(X, Y+y, Z, [y], zdir='y', colors=('red',))
  70. for x in B: # plot contours in the YZ plane
  71. Y, Z = A1, A2
  72. X = fn(x, Y, Z)
  73. cset = ax.contour(X+x, Y, Z, [x], zdir='x',colors=('red',))
  74. # must set plot limits because the contour will likely extend
  75. # way beyond the displayed level. Otherwise matplotlib extends the plot limits
  76. # to encompass all values in the contour.
  77. ax.set_zlim3d(zmin, zmax)
  78. ax.set_xlim3d(xmin, xmax)
  79. ax.set_ylim3d(ymin, ymax)
  80. plt.show()
  81. if __name__ == '__main__':
  82. plot_implicit(heart_3d)

(7)Matlab 3D心形代码

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

  1. clear; clc; close all;
  2. f = @(x, y, z)(x.^2 + 2.25*y.^2 + z.^2 - 1).^3 - ...
  3. x.^2.* z.^3 - 0.1125*y.^2.*z.^3;
  4. g = @(x, y, z)(sqrt(x.^2+y.^2)-2.5).^2 + z.^2 - 0.4^2;
  5. t = linspace(-5, 5);
  6. [x1, y1, z1] = meshgrid(t);
  7. [x2, y2, z2] = meshgrid(t);
  8. val1 = f(x1, y1, z1);
  9. val2 = g(x2, y2, z2);
  10. [p1, v1] = isosurface(x1, y1, z1, val1, 0);
  11. [p2, v2] = isosurface(x2, y2, z2, val2, 0);
  12. figure()
  13. subplot(1, 1, 1)
  14. h = patch('faces',p1,'vertices',v1,'facevertexcdata',jet(size(v1,1)),...
  15. 'facecolor','w','edgecolor','flat'); hold on;
  16. patch('faces',p2,'vertices',v2,'facevertexcdata',jet(size(v2,1)),...
  17. 'facecolor','w','edgecolor','flat');
  18. grid on; axis equal; axis([-3,3,-3,3,-1.5,1.5]); view(3)
  19. title()
  20. warning('off');
  21. T = suptitle("$I\ Love\ U\ !$");
  22. set(T,'Interpreter','latex','FontSize',24)
  23. pic_num = 1;
  24. for i = 1:20
  25. v1 = 0.98 * v1;
  26. set(h, 'vertices', v1); drawnow;
  27. F = getframe(gcf);
  28. I = frame2im(F);
  29. [I,map]=rgb2ind(I,256);
  30. if pic_num == 1
  31. imwrite(I,map,'BeatingHeart.gif','gif','Loopcount',inf,'DelayTime',0.05);
  32. else
  33. imwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05);
  34. end
  35. pic_num = pic_num + 1;
  36. end
  37. for i = 1:20
  38. v1 = v1 / 0.98;
  39. set(h, 'vertices', v1); drawnow;
  40. F = getframe(gcf);
  41. I = frame2im(F);
  42. [I,map] = rgb2ind(I,256);
  43. imwrite(I,map,'BeatingHeart.gif','gif','WriteMode','append','DelayTime',0.05);
  44. pic_num = pic_num + 1;
  45. end

(8)双心(java)

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

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import static java.lang.Math.*;
  4. public class DemoTest extends JFrame {
  5. private static final long serialVersionUID = -1284128891908775645L;
  6. // 定义加载窗口大小
  7. public static final int GAME_WIDTH = 500;
  8. public static final int GAME_HEIGHT = 500;
  9. // 获取屏幕窗口大小
  10. public static final int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
  11. public static final int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;
  12. public DemoTest() {
  13. // 设置窗口标题
  14. this.setTitle("心形曲线");
  15. // 设置窗口初始位置
  16. this.setLocation((WIDTH - GAME_WIDTH) / 2, (HEIGHT - GAME_HEIGHT) / 2);
  17. // 设置窗口大小
  18. this.setSize(GAME_WIDTH, GAME_HEIGHT);
  19. // 设置背景色
  20. this.setBackground(Color.BLACK);
  21. // 设置窗口关闭方式
  22. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23. // 设置窗口显示
  24. this.setVisible(true);
  25. }
  26. @Override
  27. public void paint(Graphics g) {
  28. double x, y, r;
  29. Image OffScreen = createImage(GAME_WIDTH, GAME_HEIGHT);
  30. Graphics drawOffScreen = OffScreen.getGraphics();
  31. for (int i = 0; i < 90; i++) {
  32. for (int j = 0; j < 90; j++) {
  33. r = Math.PI / 45 * i * (1 - Math.sin(Math.PI / 45 * j)) * 18;
  34. x = r * Math.cos(Math.PI / 45 * j) * Math.sin(Math.PI / 45 * i) + GAME_WIDTH / 2;
  35. y = -r * Math.sin(Math.PI / 45 * j) + GAME_HEIGHT / 4;
  36. //设置画笔颜色
  37. drawOffScreen.setColor(Color.PINK);
  38. // 绘制椭圆
  39. drawOffScreen.fillOval((int) x, (int) y, 2, 2);
  40. }
  41. // 生成图片
  42. g.drawImage(OffScreen, 0, 0, this);
  43. }
  44. }
  45. public static void main(String[] args) {
  46. DemoTest demo = new DemoTest();
  47. demo.setVisible(true);
  48. }
  49. }

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

  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <windows.h>
  4. #include <tchar.h>
  5. float f(float x, float y, float z) {
  6. float a = x * x + 9.0f / 4.0f * y * y + z * z - 1;
  7. return a * a * a - x * x * z * z * z - 9.0f / 80.0f * y * y * z * z * z;
  8. }
  9. float h(float x, float z) {
  10. for (float y = 1.0f; y >= 0.0f; y -= 0.001f)
  11. if (f(x, y, z) <= 0.0f)
  12. return y;
  13. return 0.0f;
  14. }
  15. int main() {
  16. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
  17. 0xc);//SetConsoleTextAttribute()是Windows系统中一个可以设置控制台窗口字体颜色和背景色的计算机函数
  18. HANDLE o = GetStdHandle(STD_OUTPUT_HANDLE);// GetStdHandle()检索指定标准设备的句柄(标准输入、标准输出或标准错误)
  19. _TCHAR buffer[25][80] = { _T(' ') };
  20. _TCHAR ramp[] = _T("vvvvvvvv");
  21. int count = 0;
  22. int count1 = 0;
  23. for (float t = 0.0f;; t += 0.1f) {
  24. int sy = 0;
  25. float s = sinf(t);
  26. float a = s * s * s * s * 0.2f;
  27. for (float z = 1.3f; z > -1.2f; z -= 0.1f) {
  28. _TCHAR *p = &buffer[sy++][0];
  29. float tz = z * (1.2f - a);
  30. for (float x = -1.5f; x < 1.5f; x += 0.05f) {
  31. float tx = x * (1.2f + a);
  32. float v = f(tx, 0.0f, tz);
  33. if (v <= 0.0f) {
  34. float y0 = h(tx, tz);
  35. float ny = 0.01f;
  36. float nx = h(tx + ny, tz) - y0;
  37. float nz = h(tx, tz + ny) - y0;
  38. float nd = 1.0f / sqrtf(nx * nx + ny * ny + nz * nz);
  39. float d = (nx + ny - nz) * nd * 0.5f + 0.5f;
  40. *p++ = ramp[(int)(d * 5.0f)];
  41. } else
  42. *p++ = ' ';
  43. }
  44. }
  45. for (sy = 0; sy < 25; sy++) {
  46. COORD coord = { 0, sy };
  47. SetConsoleCursorPosition(o, coord);//作用是设置控制台(cmd)光标位置
  48. WriteConsole(o, buffer[sy], 79, NULL, 0);//从当前光标位置开始,将字符串写入控制台屏幕缓冲区
  49. }
  50. if (count <= 22) {
  51. printf("I Love You") ;//表白内容
  52. printf(" To CSDN");// 被表白者的名字
  53. count++;
  54. } else {
  55. printf("You Are My Best Lover.\");
  56. count++;
  57. if (count >= 44) {
  58. count = 0;
  59. }
  60. }
  61. Sleep(36);//Sleep函数:执行挂起一段时间,也就是等待一段时间在继续执行
  62. }
  63. }

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

转载地址:

  1. import random
  2. from math import sin, cos, pi, log
  3. from tkinter import *
  4. CANVAS_WIDTH = 640 # 画布的宽
  5. CANVAS_HEIGHT = 480 # 画布的高
  6. CANVAS_CENTER_X = CANVAS_WIDTH / 2 # 画布中心的X轴坐标
  7. CANVAS_CENTER_Y = CANVAS_HEIGHT / 2 # 画布中心的Y轴坐标
  8. IMAGE_ENLARGE = 11 # 放大比例
  9. HEART_COLOR = "pink" # 心的颜色
  10. def heart_function(t, shrink_ratio: float = IMAGE_ENLARGE):
  11. """
  12. “爱心函数生成器”
  13. :param shrink_ratio: 放大比例
  14. :param t: 参数
  15. :return: 坐标
  16. """
  17. # 基础函数
  18. x = 16 * (sin(t) ** 3)
  19. y = -(13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
  20. # 放大
  21. x *= shrink_ratio
  22. y *= shrink_ratio
  23. # 移到画布中央
  24. x += CANVAS_CENTER_X
  25. y += CANVAS_CENTER_Y
  26. return int(x), int(y)
  27. def scatter_inside(x, y, beta=0.15):
  28. """
  29. 随机内部扩散
  30. :param x: 原x
  31. :param y: 原y
  32. :param beta: 强度
  33. :return: 新坐标
  34. """
  35. ratio_x = - beta * log(random.random())
  36. ratio_y = - beta * log(random.random())
  37. dx = ratio_x * (x - CANVAS_CENTER_X)
  38. dy = ratio_y * (y - CANVAS_CENTER_Y)
  39. return x - dx, y - dy
  40. def shrink(x, y, ratio):
  41. """
  42. 抖动
  43. :param x: 原x
  44. :param y: 原y
  45. :param ratio: 比例
  46. :return: 新坐标
  47. """
  48. force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6) # 这个参数...
  49. dx = ratio * force * (x - CANVAS_CENTER_X)
  50. dy = ratio * force * (y - CANVAS_CENTER_Y)
  51. return x - dx, y - dy
  52. def curve(p):
  53. """
  54. 自定义曲线函数,调整跳动周期
  55. :param p: 参数
  56. :return: 正弦
  57. """
  58. return 4 * (2 * sin(4 * p)) / (2 * pi)
  59. class Heart:
  60. """
  61. 爱心类
  62. """
  63. def __init__(self, generate_frame=20):
  64. self._points = set() # 原始爱心坐标集合
  65. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  66. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  67. self.all_points = {} # 每帧动态点坐标
  68. self.build(2000)
  69. self.random_halo = 1000
  70. self.generate_frame = generate_frame
  71. for frame in range(generate_frame):
  72. self.calc(frame)
  73. def build(self, number):
  74. # 爱心
  75. for _ in range(number):
  76. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  77. x, y = heart_function(t)
  78. self._points.add((x, y))
  79. # 爱心内扩散
  80. for _x, _y in list(self._points):
  81. for _ in range(3):
  82. x, y = scatter_inside(_x, _y, 0.05)
  83. self._edge_diffusion_points.add((x, y))
  84. # 爱心内再次扩散
  85. point_list = list(self._points)
  86. for _ in range(4000):
  87. x, y = random.choice(point_list)
  88. x, y = scatter_inside(x, y, 0.17)
  89. self._center_diffusion_points.add((x, y))
  90. @staticmethod
  91. def calc_position(x, y, ratio):
  92. # 调整缩放比例
  93. force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520)
  94. dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-1, 1)
  95. dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-1, 1)
  96. return x - dx, y - dy
  97. def calc(self, generate_frame):
  98. ratio = 10 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
  99. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  100. halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  101. all_points = []
  102. # 光环
  103. heart_halo_point = set() # 光环的点坐标集合
  104. for _ in range(halo_number):
  105. t = random.uniform(0, 2 * pi) # 随机不到的地方造成爱心有缺口
  106. x, y = heart_function(t, shrink_ratio=11)
  107. x, y = shrink(x, y, halo_radius)
  108. if (x, y) not in heart_halo_point:
  109. # 处理新的点
  110. heart_halo_point.add((x, y))
  111. x += random.randint(-11, 11)
  112. y += random.randint(-11, 11)
  113. size = random.choice((1, 2, 2))#控制外围粒子的大小
  114. all_points.append((x, y, size))
  115. # 轮廓
  116. for x, y in self._points:
  117. x, y = self.calc_position(x, y, ratio)
  118. size = random.randint(1, 3)
  119. all_points.append((x, y, size))
  120. # 内容
  121. for x, y in self._center_diffusion_points:
  122. x, y = self.calc_position(x, y, ratio)
  123. size = random.randint(1, 2)
  124. all_points.append((x, y, size))
  125. self.all_points[generate_frame] = all_points
  126. def render(self, render_canvas, render_frame):
  127. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  128. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=HEART_COLOR)
  129. def draw(main: Tk, render_canvas: Canvas, render_heart: Heart, render_frame=0):
  130. render_canvas.delete('all')
  131. render_heart.render(render_canvas, render_frame)
  132. main.after(160, draw, main, render_canvas, render_heart, render_frame + 1)
  133. if __name__ == '__main__':
  134. root = Tk() # 一个Tk
  135. canvas = Canvas(root, bg='black', height=CANVAS_HEIGHT, width=CANVAS_WIDTH)
  136. canvas.pack()
  137. heart = Heart() # 心
  138. draw(root, canvas, heart) # 开始画画~
  139. root.mainloop()

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

(1)一行代码画爱心

print(''.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(''.join(a))
 

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

  1. import time
  2. y = 2.5
  3. while y>=-1.6:
  4. x = -3.0
  5. while x<=4.0:
  6. 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):
  7. print(' ',end="")
  8. else:
  9. print('*',end="")
  10. x += 0.1
  11. print()
  12. time.sleep(0.25)
  13. y -= 0.2

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

  1. import time
  2. y = 2.5
  3. while y>=-1.6:
  4. x = -3.0
  5. while x<=4.0:
  6. 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):
  7. print('*',end="")
  8. else:
  9. print(' ',end="")
  10. x += 0.1
  11. print()
  12. time.sleep(0.25)
  13. y -= 0.2

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

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

  1. import time
  2. sentence = "Dear, I love you forever!"
  3. for char in sentence.split():
  4. allChar = []
  5. for y in range(12, -12, -1):
  6. lst = []
  7. lst_con = ''
  8. for x in range(-30, 30):
  9. formula = ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3
  10. if formula <= 0:
  11. lst_con += char[(x) % len(char)]
  12. else:
  13. lst_con += ' '
  14. lst.append(lst_con)
  15. allChar += lst
  16. print(''.join(allChar))
  17. 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)红玫瑰

篇幅太长,请点击查看:

(2)前端canvas玫瑰花

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <style>
  10. .flower {
  11. margin-left: 32%;
  12. margin-top: 9%;
  13. }
  14. </style>
  15. <body>
  16. <canvas id="c" class="flower"></canvas>
  17. </body>
  18. </html>
  19. <script>
  20. var b = document.body;
  21. var c = document.getElementsByTagName('canvas')[0];
  22. var a = c.getContext('2d');
  23. document.body.clientWidth;
  24. 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)
  25. </script>

五、前端特效爱心

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

  1. <html>
  2. <head></head>
  3. <body>
  4. <div class="wrapper">
  5. <input type="checkbox" id="ck1">
  6. <label for="ck1">I</label>
  7. <input type="checkbox" id="ck2">
  8. <label for="ck2">love</label>
  9. <input type="checkbox" id="ck3">
  10. <label for="ck3">you</label>
  11. </div>
  12. <span>点击每个单词查看效果</span>
  13. <style>
  14. html {
  15. display: table;
  16. width: 100%; height: 100%;
  17. table-layout: fixed;
  18. }
  19. body {
  20. display: table-cell;
  21. width: 100%; height: 100%;
  22. vertical-align: middle;
  23. font-family: 'Shadows Into Light';
  24. color: #111;
  25. }
  26. .wrapper {
  27. width: 500px; height: 500px;
  28. position: relative;
  29. margin: 0 auto;
  30. }
  31. input[type="checkbox"] {
  32. display: none;
  33. }
  34. input[type="checkbox"] + label {
  35. width: 100px; height: 100px;
  36. line-height: 100px;
  37. display: inline-block;
  38. position: absolute;
  39. text-align: center;
  40. font-size: 100px;
  41. transition: all 1s ease;
  42. }
  43. label {
  44. text-shadow: 8px 8px 30px rgba(0,0,0,0.5);
  45. }
  46. label:hover {
  47. color: #c32a2a;
  48. cursor: pointer;
  49. }
  50. #ck1 + label,
  51. #ck2 + label {
  52. border-radius: 50px;
  53. top: 0;
  54. }
  55. #ck1:checked + label,
  56. #ck2:checked + label,
  57. #ck3:checked + label {
  58. background: #c32a2a;
  59. font-size: 0;
  60. transition: all 1s ease;
  61. }
  62. #ck1:checked + label,
  63. #ck2:checked + label {
  64. width: 300px; height: 300px;
  65. border-radius: 150px;
  66. line-height: 300px;
  67. }
  68. #ck1 + label {
  69. left: 0;
  70. }
  71. #ck2 + label {
  72. right: 0;
  73. }
  74. #ck3 + label {
  75. bottom: 0; left: 50%;
  76. margin: 0 -50px;
  77. }
  78. #ck3:checked + label {
  79. width: 275px; height: 275px;
  80. bottom: 96px; left: 162px;
  81. transform: rotate(45deg);
  82. line-height: 27px;
  83. }
  84. span {
  85. display: inline-block;
  86. text-align: center;
  87. position: absolute;
  88. bottom: 10px; left: 50%;
  89. margin-left: -100px;
  90. width: 200px;
  91. font-size: 24px;
  92. color: #999;
  93. }
  94. </style>
  95. </body>
  96. </html>

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

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script src="https://cdn.staticfile.org/d3/4.13.0/d3.min.js"></script>
  9. <style>
  10. body {
  11. margin: 0;
  12. height: 100vh;
  13. display: flex;
  14. align-items: center;
  15. justify-content: center;
  16. background-color: black;
  17. overflow: hidden;
  18. }
  19. .love {
  20. width: 450px;
  21. height: 450px;
  22. position: relative;
  23. }
  24. .love span {
  25. position: absolute;
  26. left: 0;
  27. color: goldenrod;
  28. font-size: 20px;
  29. font-family: sans-serif;
  30. text-shadow: 0 0 1em white;
  31. animation:
  32. x-move 10s ease-in-out infinite alternate,
  33. y-move 20s linear infinite;
  34. animation-delay: calc(20s / var(--particles) * var(--n) * -1);
  35. user-select: none;
  36. }
  37. .love span:first-child {
  38. color: orangered;
  39. font-size: 3em;
  40. text-shadow:
  41. 0 0 0.1em black,
  42. 0 0 1em white;
  43. z-index: 1;
  44. }
  45. @keyframes x-move {
  46. to {
  47. left: 450px;
  48. }
  49. }
  50. @keyframes y-move {
  51. 0% { transform: translateY(180px); }
  52. 10% { transform: translateY(45px); }
  53. 15% { transform: translateY(5px); }
  54. 18% { transform: translateY(0); }
  55. 20% { transform: translateY(5px); }
  56. 22% { transform: translateY(35px); }
  57. 24% { transform: translateY(65px); }
  58. 25% { transform: translateY(110px); }
  59. 26% { transform: translateY(65px); }
  60. 28% { transform: translateY(35px); }
  61. 30% { transform: translateY(5px); }
  62. 32% { transform: translateY(0); }
  63. 35% { transform: translateY(5px); }
  64. 40% { transform: translateY(45px); }
  65. 50% { transform: translateY(180px); }
  66. 71% { transform: translateY(430px); }
  67. 72.5% { transform: translateY(440px); }
  68. 75% { transform: translateY(450px); }
  69. 77.5% { transform: translateY(440px); }
  70. 79% { transform: translateY(430px); }
  71. 100% { transform: translateY(180px); }
  72. }
  73. </style>
  74. </head>
  75. <body>
  76. <div class="love"></div>
  77. </body>
  78. </html>
  79. <script>
  80. const words = [
  81. '爱', 'Love', 'Amour', 'Liebe', 'Amore',
  82. 'Amor', 'Любовь', 'الحب', 'प्यार', 'Cinta',
  83. 'Αγάπη', '사랑', 'Liefde', 'Dashuri', 'Каханне',
  84. 'Ljubav', 'Láska', 'Armastus', 'Mahal', 'אהבה',
  85. 'Szerelem', 'Grá', 'Mīlestība', 'Meilė', 'Любов',
  86. 'Љубовта', 'Cinta', 'عشق', 'Dragoste', 'Láska',
  87. 'Renmen', 'ፍቅር', 'munaña', 'Sevgi', 'Љубав',
  88. 'karout', 'amà', 'amôr', 'kærleiki', 'mborayhu',
  89. 'Upendo', 'sòòyayyàà', 'ljubav', 'Սեր', 'сүю',
  90. 'сүйүү', 'tia', 'aroha', 'KHAIR', 'प्रेम',
  91. 'kjærlighet', 'munay', 'jecel', 'Kärlek', 'soymek',
  92. 'Mahal', 'ярату', 'محبت', 'sopp', 'uthando',
  93. 'ความรัก', 'Aşk', 'Tình yêu', 'ליבע'];
  94. d3.select('.love')
  95. .style('--particles', words.length)
  96. .selectAll('span')
  97. .data(words)
  98. .enter()
  99. .append('span')
  100. .style('--n', (d, i) => i + 1)
  101. .text((d) => d);
  102. </script>

(3)上升爱心效果

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <canvas id="cavs"></canvas>
  11. </body>
  12. </html>
  13. <script>
  14. var canvas = document.getElementById("cavs");
  15. const WIDTH = window.innerWidth;
  16. const HEIGHT = window.innerHeight;
  17. canvas.setAttribute("width", WIDTH);
  18. canvas.setAttribute("height", HEIGHT);
  19. var context = canvas.getContext("2d");
  20. var start =
  21. {
  22. loves: [],
  23. DURATION: 30,
  24. begin: function () {
  25. this.createLove();
  26. },
  27. createLove: function () {
  28. for (var i = 0; i < WIDTH / 59; i++) {
  29. var love = new Love();
  30. this.loves.push(love);
  31. }
  32. setInterval(this.drawLove.bind(this), this.DURATION);
  33. },
  34. drawLove: function () {
  35. context.clearRect(0, 0, WIDTH, HEIGHT);
  36. for (var key in this.loves) {
  37. this.loves[key].draw();
  38. }
  39. }
  40. }
  41. function Love() {
  42. var me = this;
  43. function rand() {
  44. me.attr.scale = (Math.random() * 0.8 + 0.3) * WIDTH / 521;
  45. me.attr.x = Math.floor(Math.random() * WIDTH - 40);
  46. me.attr.y = Math.floor(HEIGHT - Math.random() * 200);
  47. me.attr.ColR = Math.floor(Math.random() * 255);
  48. me.attr.ColG = Math.floor(Math.random() * 255);
  49. me.attr.ColB = Math.floor(Math.random() * 255);
  50. me.attr.alpha = Math.random() * 0.2 + 0.8;
  51. me.attr.vector = Math.random() * 5 + 0.4;
  52. }
  53. (function () { me.attr = {}; rand(); }());
  54. me.draw = function () {
  55. if (me.attr.alpha < 0.01) rand();
  56. x = me.attr.x;
  57. y = me.attr.y;
  58. scale = 4 * me.attr.scale;
  59. context.beginPath();
  60. context.bezierCurveTo(x + 2.5 * scale, y + 2.5 * scale, x + 2.0 * scale, y, x, y);
  61. context.bezierCurveTo(x - 3.0 * scale, y, x - 3.0 * scale, y + 3.5 * scale, x - 3.0 * scale, y + 3.5 * scale);
  62. 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);
  63. 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);
  64. context.bezierCurveTo(x + 8.0 * scale, y + 3.5 * scale, x + 8.0 * scale, y, x + 5.0 * scale, y);
  65. context.bezierCurveTo(x + 3.5 * scale, y, x + 2.5 * scale, y + 2.5 * scale, x + 2.5 * scale, y + 2.5 * scale);
  66. context.fillStyle = "rgba(" + me.attr.ColR + "," + me.attr.ColG + "," + me.attr.ColB + "," + me.attr.alpha + ")";
  67. context.fill();
  68. context.lineWidth = 0.5;
  69. context.stroke();
  70. me.attr.y -= me.attr.vector;
  71. me.attr.alpha -= (me.attr.vector / 2.9 * 3.5 / HEIGHT);
  72. }
  73. }
  74. window.onload = function () {
  75. start.begin();
  76. }
  77. </script>

(4)变幻爱心

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <canvas id="c"></canvas>
  11. </body>
  12. </html>
  13. <script>
  14. var b = document.body,
  15. c = document.getElementsByTagName('canvas')[0],
  16. a = c.getContext('2d');
  17. document.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218
  18. // ### Pixel Love - a js1k 2012 entry by @aaronsnoswell
  19. // This demo is on [github](https://github.com/aaronsnoswell/js1k-2012-love)
  20. // 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/)
  21. // Define some variables:
  22. var h = "❤", // A heart
  23. g = 5, // The granularity - determines the size of each 'pixel'
  24. l = 10, // The threshold / limit, used for determining where to place pixels
  25. outline = [], // Arrays of locations for the outline and fill pixles
  26. fill = [],
  27. sx = 100, // Where to draw the heart
  28. sy = 450,
  29. box = [999, 999, 0, 0]; // The bounding box of the heart (computed later)
  30. // Set the canvas size
  31. c.width = 500;
  32. c.height = 800;
  33. // A utility function, used for looping over an x and y variable
  34. var loopxy = function(w, h, step, callback) {
  35. for(var x=0; x<w; x+=step) {
  36. for(var y=0; y<h; y+=step) {
  37. callback(x, y, step);
  38. }
  39. }
  40. }
  41. // Shortcut method for clearing the canvas
  42. a.clear = function() {
  43. a.clearRect(0, 0, c.width, c.height);
  44. }
  45. // Normalise browser font rendering in the canvas.
  46. // See [https://twitter.com/#!/aaronsnoswell/status/165642474109419520](https://twitter.com/#!/aaronsnoswell/status/165642474109419520)
  47. a.textBaseline = "bottom";
  48. a.font="300pt arial";
  49. a.lineWidth = g*2;
  50. // Draw a filled heart on the canvas
  51. a.fillText(h, sx, sy);
  52. // Loop over the entire canvas and wherever there are filled pixels,
  53. // store that location in the fill array
  54. var d = a.getImageData(0, 0, c.width, c.height)
  55. loopxy(d.width, d.height, g, function(x, y) {
  56. if(d.data[(x + y*d.width)*4+3] >= l) fill.push([x, y]);
  57. });
  58. // Clear the screen
  59. a.clear();
  60. // Draw an outline of a heart on the canvas
  61. a.strokeText(h, sx, sy);
  62. // Loop over the entire canvas once again. Wherever there are filled
  63. // pixels, store that location in the outline array
  64. var d = a.getImageData(0, 0, c.width, c.height)
  65. loopxy(d.width, d.height, g, function(x, y) {
  66. if(d.data[(x + y*d.width)*4+3] >= l) {
  67. outline.push([x, y]);
  68. // Compute the bounding box of the heart
  69. if(x<box[0]) box[0] = x;
  70. if(x>box[2]) box[2] = x;
  71. if(y<box[1]) box[1] = y;
  72. if(y>box[3]) box[3] = y;
  73. }
  74. });
  75. // Find the middle x and y locations of the heart
  76. box.push((box[0]+box[2])/2);
  77. box.push((box[1]+box[3])/2);
  78. // Store the current time as ms since epoch
  79. var t0 = new Date().getTime();
  80. // Use a recursive named function + setTimeout to ensure each frame has
  81. // time to finish before the next one is drawn
  82. (function render() {
  83. window.setTimeout(function() {
  84. // Time delta and elapsed time
  85. var d = new Date().getTime()-t0;
  86. t0 += d;
  87. // Clear the screen
  88. a.clear();
  89. // Draw the red heart
  90. a.fillStyle = "#f00";
  91. loopxy(fill.length, 1, 1, function(i) {
  92. var x = fill[i][0],
  93. y = fill[i][1];
  94. // Offset each pixel by a sinusoidal, time based ammount
  95. a.fillRect(x-g/2+Math.sin(t0/500+y/80)*(x-box[4])+10, y-g/2+10, g, g);
  96. })
  97. // Draw the outline using the same logic as above
  98. a.fillStyle = "#000";
  99. loopxy(outline.length, 1, 1, function(i) {
  100. var x = outline[i][0],
  101. y = outline[i][1];
  102. a.fillRect(x-g/2+Math.sin(t0/500+y/80)*(x-box[4])+10, y-g/2+10, g, g);
  103. })
  104. // Loop at 30fps
  105. render();
  106. }, 1/30);
  107. })();
  108. </script>

(5)红心下落动画

原:

  1. <html>
  2. <canvas></canvas>
  3. <script>
  4. var c = document.getElementsByTagName('canvas')[0];
  5. var b = document.body;
  6. var a = c.getContext('2d');
  7. function d(b, c, d, e) {
  8. a.fillStyle = b;
  9. a.beginPath();
  10. a.arc(c, d, e, 0, 2 * m.PI, !0);
  11. a.fill();
  12. a.fillRect(c, d, 1, 1)
  13. }
  14. m = Math;
  15. r = m.random;
  16. g = Date;
  17. l = +(new g);
  18. e = document;
  19. q = e.createElement("canvas");
  20. w = e.createElement("canvas");
  21. o = {};
  22. h = 100;
  23. H = 200;
  24. v = window;
  25. t = c.width = v.innerWidth;
  26. u = c.height = v.innerHeight - 5;
  27. b.setAttribute("style", "margin:0;background:#000");
  28. k = a;
  29. q.width = q.height = h;
  30. w.width = 1e3;
  31. w.height = H;
  32. for (j = 0; ++j < H; ) {
  33. for (i = 0; 1e3 > ++i; )
  34. a = q.getContext("2d"),
  35. z = .5 - i / h,
  36. f = j / h - .5 + .4 * m.sqrt(m.abs(z)),
  37. f = z * z + 2 * f * f,
  38. .23 > f && d(.16 < f ? "#F00" : "#F88", i, j, 0),
  39. a = w.getContext("2d"),
  40. d(j > 5e-4 * i * i - .3 * i + h ? "#343" : j > 4e-4 * i * i - .9 * i + 500 ? "#232" : "#000", i, j, 0);
  41. o[j] = {
  42. x: r() * t,
  43. y: -h - r() * u,
  44. b: 51 - j / 4,
  45. a: 25 + .4 * j
  46. };
  47. o[H + j] = {
  48. x: r() * t,
  49. y: r() * u - H,
  50. a: 3 * r() + 1,
  51. c: j
  52. }
  53. }
  54. a = k;
  55. v.setInterval(function() {
  56. n = +(new g);
  57. a.clearRect(0, 0, t, u);
  58. d("#FFA", H, 250, 150);
  59. d("#000", 270, 320, h);
  60. a.drawImage(w, 0, u - H, t, H);
  61. for (i = 0; ++i < H; )
  62. f = (n - l) / h,
  63. s = o[H + i],
  64. d("#FFA", s.x, s.y, m.floor(m.max(s.a + m.sin(s.c++ / 10) - .5, 1))),
  65. z = o[i],
  66. a.drawImage(q, z.x += -.1 / (z.b / h) * f, z.y += (5 - z.b / 10) * f, z.a, z.a),
  67. z.y > u && (z.y = -h),
  68. z.x < -H && (z.x = t);
  69. l = n
  70. }, 60)
  71. //L<3
  72. </script>
  73. </html>

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

转载地址:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <HTML>
  3. <HEAD>
  4. <TITLE> New Document </TITLE>
  5. <META NAME="Generator" CONTENT="EditPlus">
  6. <META NAME="Author" CONTENT="">
  7. <META NAME="Keywords" CONTENT="">
  8. <META NAME="Description" CONTENT="">
  9. <style>
  10. html, body {
  11. height: 100%;
  12. padding: 0;
  13. margin: 0;
  14. background: #000;
  15. }
  16. canvas {
  17. position: absolute;
  18. width: 100%;
  19. height: 100%;
  20. }
  21. </style>
  22. </HEAD>
  23. <BODY>
  24. <canvas id="pinkboard"></canvas>
  25. <script>
  26. /*
  27. * Settings
  28. */
  29. var settings = {
  30. particles: {
  31. length: 500, // maximum amount of particles
  32. duration: 2, // particle duration in sec
  33. velocity: 100, // particle velocity in pixels/sec
  34. effect: -0.75, // play with this for a nice effect
  35. size: 30, // particle size in pixels
  36. },
  37. };
  38. /*
  39. * RequestAnimationFrame polyfill by Erik Möller
  40. */
  41. (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)}}}());
  42. /*
  43. * Point class
  44. */
  45. var Point = (function() {
  46. function Point(x, y) {
  47. this.x = (typeof x !== 'undefined') ? x : 0;
  48. this.y = (typeof y !== 'undefined') ? y : 0;
  49. }
  50. Point.prototype.clone = function() {
  51. return new Point(this.x, this.y);
  52. };
  53. Point.prototype.length = function(length) {
  54. if (typeof length == 'undefined')
  55. return Math.sqrt(this.x * this.x + this.y * this.y);
  56. this.normalize();
  57. this.x *= length;
  58. this.y *= length;
  59. return this;
  60. };
  61. Point.prototype.normalize = function() {
  62. var length = this.length();
  63. this.x /= length;
  64. this.y /= length;
  65. return this;
  66. };
  67. return Point;
  68. })();
  69. /*
  70. * Particle class
  71. */
  72. var Particle = (function() {
  73. function Particle() {
  74. this.position = new Point();
  75. this.velocity = new Point();
  76. this.acceleration = new Point();
  77. this.age = 0;
  78. }
  79. Particle.prototype.initialize = function(x, y, dx, dy) {
  80. this.position.x = x;
  81. this.position.y = y;
  82. this.velocity.x = dx;
  83. this.velocity.y = dy;
  84. this.acceleration.x = dx * settings.particles.effect;
  85. this.acceleration.y = dy * settings.particles.effect;
  86. this.age = 0;
  87. };
  88. Particle.prototype.update = function(deltaTime) {
  89. this.position.x += this.velocity.x * deltaTime;
  90. this.position.y += this.velocity.y * deltaTime;
  91. this.velocity.x += this.acceleration.x * deltaTime;
  92. this.velocity.y += this.acceleration.y * deltaTime;
  93. this.age += deltaTime;
  94. };
  95. Particle.prototype.draw = function(context, image) {
  96. function ease(t) {
  97. return (--t) * t * t + 1;
  98. }
  99. var size = image.width * ease(this.age / settings.particles.duration);
  100. context.globalAlpha = 1 - this.age / settings.particles.duration;
  101. context.drawImage(image, this.position.x - size / 2, this.position.y - size / 2, size, size);
  102. };
  103. return Particle;
  104. })();
  105. /*
  106. * ParticlePool class
  107. */
  108. var ParticlePool = (function() {
  109. var particles,
  110. firstActive = 0,
  111. firstFree = 0,
  112. duration = settings.particles.duration;
  113. function ParticlePool(length) {
  114. // create and populate particle pool
  115. particles = new Array(length);
  116. for (var i = 0; i < particles.length; i++)
  117. particles[i] = new Particle();
  118. }
  119. ParticlePool.prototype.add = function(x, y, dx, dy) {
  120. particles[firstFree].initialize(x, y, dx, dy);
  121. // handle circular queue
  122. firstFree++;
  123. if (firstFree == particles.length) firstFree = 0;
  124. if (firstActive == firstFree ) firstActive++;
  125. if (firstActive == particles.length) firstActive = 0;
  126. };
  127. ParticlePool.prototype.update = function(deltaTime) {
  128. var i;
  129. // update active particles
  130. if (firstActive < firstFree) {
  131. for (i = firstActive; i < firstFree; i++)
  132. particles[i].update(deltaTime);
  133. }
  134. if (firstFree < firstActive) {
  135. for (i = firstActive; i < particles.length; i++)
  136. particles[i].update(deltaTime);
  137. for (i = 0; i < firstFree; i++)
  138. particles[i].update(deltaTime);
  139. }
  140. // remove inactive particles
  141. while (particles[firstActive].age >= duration && firstActive != firstFree) {
  142. firstActive++;
  143. if (firstActive == particles.length) firstActive = 0;
  144. }
  145. };
  146. ParticlePool.prototype.draw = function(context, image) {
  147. // draw active particles
  148. if (firstActive < firstFree) {
  149. for (i = firstActive; i < firstFree; i++)
  150. particles[i].draw(context, image);
  151. }
  152. if (firstFree < firstActive) {
  153. for (i = firstActive; i < particles.length; i++)
  154. particles[i].draw(context, image);
  155. for (i = 0; i < firstFree; i++)
  156. particles[i].draw(context, image);
  157. }
  158. };
  159. return ParticlePool;
  160. })();
  161. /*
  162. * Putting it all together
  163. */
  164. (function(canvas) {
  165. var context = canvas.getContext('2d'),
  166. particles = new ParticlePool(settings.particles.length),
  167. particleRate = settings.particles.length / settings.particles.duration, // particles/sec
  168. time;
  169. // get point on heart with -PI <= t <= PI
  170. function pointOnHeart(t) {
  171. return new Point(
  172. 160 * Math.pow(Math.sin(t), 3),
  173. 130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25
  174. );
  175. }
  176. // creating the particle image using a dummy canvas
  177. var image = (function() {
  178. var canvas = document.createElement('canvas'),
  179. context = canvas.getContext('2d');
  180. canvas.width = settings.particles.size;
  181. canvas.height = settings.particles.size;
  182. // helper function to create the path
  183. function to(t) {
  184. var point = pointOnHeart(t);
  185. point.x = settings.particles.size / 2 + point.x * settings.particles.size / 350;
  186. point.y = settings.particles.size / 2 - point.y * settings.particles.size / 350;
  187. return point;
  188. }
  189. // create the path
  190. context.beginPath();
  191. var t = -Math.PI;
  192. var point = to(t);
  193. context.moveTo(point.x, point.y);
  194. while (t < Math.PI) {
  195. t += 0.01; // baby steps!
  196. point = to(t);
  197. context.lineTo(point.x, point.y);
  198. }
  199. context.closePath();
  200. // create the fill
  201. context.fillStyle = '#ea80b0';
  202. context.fill();
  203. // create the image
  204. var image = new Image();
  205. image.src = canvas.toDataURL();
  206. return image;
  207. })();
  208. // render that thing!
  209. function render() {
  210. // next animation frame
  211. requestAnimationFrame(render);
  212. // update time
  213. var newTime = new Date().getTime() / 1000,
  214. deltaTime = newTime - (time || newTime);
  215. time = newTime;
  216. // clear canvas
  217. context.clearRect(0, 0, canvas.width, canvas.height);
  218. // create new particles
  219. var amount = particleRate * deltaTime;
  220. for (var i = 0; i < amount; i++) {
  221. var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random());
  222. var dir = pos.clone().length(settings.particles.velocity);
  223. particles.add(canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y);
  224. }
  225. // update and draw particles
  226. particles.update(deltaTime);
  227. particles.draw(context, image);
  228. }
  229. // handle (re-)sizing of the canvas
  230. function onResize() {
  231. canvas.width = canvas.clientWidth;
  232. canvas.height = canvas.clientHeight;
  233. }
  234. window.onresize = onResize;
  235. // delay rendering bootstrap
  236. setTimeout(function() {
  237. onResize();
  238. render();
  239. }, 10);
  240. })(document.getElementById('pinkboard'));
  241. </script>
  242. </BODY>
  243. </HTML>

六、特色推荐

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

     推荐阅读:

23

22

21

20

19

​​

18

​​​

17

​​​

16

​​​

15

​​​

14

​​​

13

​​​

12

​​​

11

​​​

10

​​​

9

​​​

8

​​​

7

​​​

6

​​​

5

​​​

4

​​​

3

​​​

2

​​​

1

​​​

sss

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发