HTML表白程序,一定要收藏好

本文展示了如何使用HTML5的CanvasAPI创建三种不同的动画效果:粉色爱心飘动、爱心树生长及玫瑰绽放。代码中包含了粒子系统、图形绘制和时间同步等技术,用于在网页上生成动态的视觉表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 粉色爱心

效果

<!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 particles
    duration:   2, // particle duration in sec
    velocity: 100, // particle velocity in pixels/sec
    effect: -0.75, // play with this for a nice effect
    size:      30, // particle size in pixels
  },
};

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

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

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

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

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

效果

代码如下

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>爱心树表白动画</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        background: #fafafa;
        font-size: 14px;
        font-family: "微软雅黑", "宋体", sans-serif;
        color: #231f20;
        overflow: auto;
      }
      a {
        color: #000;
        font-size: 14px;
      }
      #main {
        width: 100%;
      }
      #wrap {
        position: relative;
        margin: 0 auto;
        width: 1100px;
        height: 680px;
        margin-top: 10px;
      }
      #text {
        width: 400px;
        height: 425px;
        left: 60px;
        top: 80px;
        position: absolute;
      }
      #code {
        display: none;
        font-size: 16px;
      }
      #clock-box {
        position: absolute;
        left: 60px;
        top: 550px;
        font-size: 28px;
        display: none;
      }
      #clock-box a {
        font-size: 28px;
        text-decoration: none;
      }
      #clock {
        margin-left: 48px;
      }
      #clock .digit {
        font-size: 64px;
      }
      #canvas {
        margin: 0 auto;
        width: 1100px;
        height: 680px;
      }
      #error {
        margin: 0 auto;
        text-align: center;
        margin-top: 60px;
        display: none;
      }
      .hand {
        cursor: pointer;
      }
      .say {
        margin-left: 5px;
      }
      .space {
        margin-right: 150px;
      }
    </style>
  </head>
  <body>
    <div id="main">
      <div id="error">
        抱歉!目前您的浏览器无法显示,请更新至最新版本或使用其他主流浏览器,谢谢合作。
      </div>
      <div id="wrap">
        <canvas id="canvas" width="1100" height="680"></canvas>
      </div>
    </div>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jquery.min.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex.min.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex-parser.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex-jit.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex-builderbase.min.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex-async.min.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/jscex-async-powerpack.min.js"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/functions.js"
      charset="utf-8"
    ></script>
    <script
      type="text/javascript"
      src="https://cdn-static-devbit.youkuaiyun.com/devbit-static/code/love-tree/js/love.js"
      charset="utf-8"
    ></script>
    <script>
      (function () {
        var canvas = $("#canvas");
        if (!canvas[0].getContext) {
          $("#error").show();
          return false;
        }

        var width = canvas.width();
        var height = canvas.height();
        canvas.attr("width", width);
        canvas.attr("height", height);
        var opts = {
          seed: {
            x: width / 2 - 20,
            color: "rgb(190, 26, 37)",
            scale: 2
          },
          branch: [
            [
              535,
              680,
              570,
              250,
              500,
              200,
              30,
              100,
              [
                [
                  540,
                  500,
                  455,
                  417,
                  340,
                  400,
                  13,
                  100,
                  [[450, 435, 434, 430, 394, 395, 2, 40]]
                ],
                [
                  550,
                  445,
                  600,
                  356,
                  680,
                  345,
                  12,
                  100,
                  [[578, 400, 648, 409, 661, 426, 3, 80]]
                ],
                [539, 281, 537, 248, 534, 217, 3, 40],
                [
                  546,
                  397,
                  413,
                  247,
                  328,
                  244,
                  9,
                  80,
                  [
                    [427, 286, 383, 253, 371, 205, 2, 40],
                    [498, 345, 435, 315, 395, 330, 4, 60]
                  ]
                ],
                [
                  546,
                  357,
                  608,
                  252,
                  678,
                  221,
                  6,
                  100,
                  [[590, 293, 646, 277, 648, 271, 2, 80]]
                ]
              ]
            ]
          ],
          bloom: {
            num: 700,
            width: 1080,
            height: 650
          },
          footer: {
            width: 1200,
            height: 5,
            speed: 10
          }
        };

        var tree = new Tree(canvas[0], width, height, opts);
        var seed = tree.seed;
        var foot = tree.footer;
        var hold = 1;

        canvas
          .click(function (e) {
            var offset = canvas.offset(),
              x,
              y;
            x = e.pageX - offset.left;
            y = e.pageY - offset.top;
            if (seed.hover(x, y)) {
              hold = 0;
              canvas.unbind("click");
              canvas.unbind("mousemove");
              canvas.removeClass("hand");
            }
          })
          .mousemove(function (e) {
            var offset = canvas.offset(),
              x,
              y;
            x = e.pageX - offset.left;
            y = e.pageY - offset.top;
            canvas.toggleClass("hand", seed.hover(x, y));
          });

        var seedAnimate = eval(
          Jscex.compile("async", function () {
            seed.draw();
            while (hold) {
              $await(Jscex.Async.sleep(10));
            }
            while (seed.canScale()) {
              seed.scale(0.95);
              $await(Jscex.Async.sleep(10));
            }
            while (seed.canMove()) {
              seed.move(0, 2);
              foot.draw();
              $await(Jscex.Async.sleep(10));
            }
          })
        );

        var growAnimate = eval(
          Jscex.compile("async", function () {
            do {
              tree.grow();
              $await(Jscex.Async.sleep(10));
            } while (tree.canGrow());
          })
        );

        var flowAnimate = eval(
          Jscex.compile("async", function () {
            do {
              tree.flower(2);
              $await(Jscex.Async.sleep(10));
            } while (tree.canFlower());
          })
        );

        var moveAnimate = eval(
          Jscex.compile("async", function () {
            tree.snapshot("p1", 240, 0, 610, 680);
            canvas
              .parent()
              .css("background", "url(" + tree.toDataURL("image/png") + ")");
            canvas.css("background", "#fafafa");
            $await(Jscex.Async.sleep(300));
            canvas.css("background", "none");
          })
        );

        var jumpAnimate = eval(
          Jscex.compile("async", function () {
            var ctx = tree.ctx;
            while (true) {
              tree.ctx.clearRect(0, 0, width, height);
              tree.jump();
              foot.draw();
              $await(Jscex.Async.sleep(25));
            }
          })
        );

        var textAnimate = eval(
          Jscex.compile("async", function () {
            var together = new Date();
            together.setFullYear(2010, 1, 15); //时间年月日
            together.setHours(16); //小时
            together.setMinutes(53); //分钟
            together.setSeconds(0); //秒前一位
            together.setMilliseconds(2); //秒第二位

            $("#code").show().typewriter();
            $("#clock-box").fadeIn(500);
            while (true) {
              timeElapse(together);
              $await(Jscex.Async.sleep(1000));
            }
          })
        );

        var runAsync = eval(
          Jscex.compile("async", function () {
            $await(seedAnimate());
            $await(growAnimate());
            $await(flowAnimate());
            $await(moveAnimate());
            $await(jumpAnimate());
          })
        );

        runAsync().start();
      })();
    </script>
  </body>
</html>
  1. 玫瑰表白代码

效果

代码

<!DOCTYPE html>
<html>
<head>
<title>玫瑰</title>
<meta charset="utf-8">
</head>
<body>
<p style="text-align: center;">
<canvas id="c" height="500" width="500"></canvas>
<script>
 var b = document.body;
 var c = document.getElementsByTagName('canvas')[0];
 var a = c.getContext('2d');
 document.body.clientWidth;
</script>
<script>
// start of submission //
with(m=Math)C=cos,S=sin,P=pow,R=random;c.width=c.height=f=500;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)
// end of submission //
</script><br>
</p>
</body>
</html>

爱心雨代码

效果

代码

<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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值