前端开发——爱心代码&DOM部分学习(一)

前言

很高兴来到csdn!能够和大家一起分享和学习,在接下来的一段时间我将和大家一起学习计算机相关技术,也希望以后能够和大家分享更多(未接触)知识!在接下来的这个寒假期间,我也将更新一些关于我最近一段时间学的知识,还有最近,我正在学习前端,如果有一些大佬可以指点一下我,我会非常欢迎并感谢的!

知识分享

1.爱心代码

插曲

最近一段时间网上最火的一部剧关于点燃了我,温暖了我这部电视剧,剧中主角李峋用用代码实现了动态爱心代码实现,让很多学计算机同学都在深刻的琢磨着,也让很多不是计算机专业的的人,痴迷计算机。

这个图其实是动态的,只是本人目前还不知道如何将动态图展现出来!大家先凑活一下看看吧,如果可以的话大家复制代码去运行就可以看到动态结果了。

 

下面就有关于李峋代码的python实现版:

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 = "red"  # 心的颜色


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

    # 放大
    x *= shrink_ratio
    y *= shrink_ratio

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

    return int(x), int(y)


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

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

    return x - dx, y - dy


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


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


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

    def __init__(self, generate_frame=20):
        self._points = set()  # 原始爱心坐标集合
        self._edge_diffusion_points = set()  # 边缘扩散效果点坐标集合
        self._center_diffusion_points = set()  # 中心扩散效果点坐标集合
        self.all_points = {}  # 每帧动态点坐标
        self.build(2000)

        self.random_halo = 1000

        self.generate_frame = generate_frame
        for frame in range(generate_frame):
            self.calc(frame)

    def build(self, number):
        # 爱心
        for _ in range(number):
            t = random.uniform(0, 2 * pi)  # 随机不到的地方造成爱心有缺口
            x, y = heart_function(t)
            self._points.add((x, y))

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

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

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

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

        return x - dx, y - dy

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

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

        all_points = []

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

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

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

        self.all_points[generate_frame] = all_points

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


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


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

爱心代码( 前端实现):

运行效果如下:

这段代码其实也是动态的,大家可以复制代码去看看效果

 代码实现:

<!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>
    <style>
        html,
        body {
            border: 0;
            padding: 0;
            margin: 0;
            overflow: hidden;
            background: #000;
            }
            
            .info {
            z-index: 999;
            position: absolute;
            left: 0;
            top: 0;
            padding: 10px;
            color: #fff;
            background: rgba(0, 0, 0, 0.5);
            text-transform: capitalize;
        }
    

    </style>
</head>
<body>
    <canvas width="300" height="300" style="width:100%;height:100vh;" id="c"></canvas>
    <script>
        var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var height = void 0,
  width = void 0,
  innerpoints = [],
  outerpoints = [],
  particles = [];
 
var noofpoints = 200,
  trashold = 10;
var x = void 0,
  y = void 0,
  p = void 0,
  n = void 0,
  point = void 0,
  dx = void 0,
  dy = void 0,
  color = void 0;
(deltaangle = (Math.PI * 2) / noofpoints), (r = Math.min(height, width) * 0.5);
 
var distance = function distance(x1, y1, x2, y2) {
  return Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
};
var mapVal = function mapVal(num, in_min, in_max, out_min, out_max) {
  return ((num - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min;
};
var resize = function resize() {
  height = ctx.canvas.clientHeight;
  width = ctx.canvas.clientWidth;
 
  if (
    ctx.canvas.clientWidth !== canvas.width ||
    ctx.canvas.clientHeight !== canvas.height
  ) {
    console.log("resized");
    canvas.width = width;
    canvas.height = height;
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate(-Math.PI);
    innerpoints = [];
    r = 10;
    for (var i = deltaangle; i <= Math.PI * 2; i += deltaangle) {
      x = r * 16 * Math.pow(Math.sin(i), 3);
      y =
        r *
        (13 * Math.cos(i) -
          5 * Math.cos(2 * i) -
          2 * Math.cos(3 * i) -
          Math.cos(4 * i));
      innerpoints.push({
        x: x,
        y: y,
      });
 
      x = 10 * r * 16 * Math.pow(Math.sin(i), 3);
      y =
        10 *
        r *
        (13 * Math.cos(i) -
          5 * Math.cos(2 * i) -
          2 * Math.cos(3 * i) -
          Math.cos(4 * i));
      outerpoints.push({
        x: x,
        y: y,
      });
 
      var step = random(0.001, 0.003, true);
      particles.push({
        step: step,
        x: x,
        y: y,
      });
    }
  }
};
var random = function random(min, max, isFloat) {
  if (isFloat) {
    return Math.random() * (max - min) + min;
  }
  return ~~(Math.random() * (max - min) + min);
};
 
resize();
 
//particles = [...outerpoints];
ctx.globalAlpha = 0.5;
ctx.globalCompositeOperation = "source-over";
var draw = function draw() {
  ctx.fillStyle = "rgba(0,0,0,0.03)";
  ctx.fillRect(-width, -height, width * 2, height * 2);
  ctx.beginPath();
 
  for (var i = 0; i < innerpoints.length; i++) {
    s = outerpoints[i];
    d = innerpoints[i];
    point = particles[i];
 
    if (distance(point.x, point.y, d.x, d.y) > 10) {
      dx = d.x - s.x;
      dy = d.y - s.y;
 
      point.x += dx * point.step;
      point.y += dy * point.step;
      color = distance(0, 0, point.x, point.y);
      ctx.beginPath();
      ctx.fillStyle = "hsl(" + (color % 360) + ",100%,50%)";
      ctx.arc(point.x, point.y, 2, 0, Math.PI * 2, false);
      ctx.closePath();
      ctx.fill();
    } else {
      point.x = d.x;
      point.y = d.y;
      ctx.beginPath();
      ctx.arc(point.x, point.y, 2, 0, Math.PI * 2, false);
      ctx.closePath();
      ctx.fill();
      particles[i].x = s.x;
      particles[i].y = s.y;
      particles[i].step = random(0.001, 0.003, true);
    }
  }
};
 
var render = function render() {
  resize();
  draw();
  requestAnimationFrame(render);
};
 
requestAnimationFrame(render);

    </script>
</body>
</html>

2.DOM学习部分

通过className改变元素属性

代码实现:

<!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>通过className来修改元素属性</title>
</head>
<style>
    div{
        height: 50px;
        width: 50px;
        background-color: pink;
        color: #999;
    }
    .change{
        background-color:aqua;
        margin-top: 100px;
        color: green;
    }
</style>
<body>
    <div>文字</div>
    <script>
        var div=document.querySelector('div');
        div.onclick=function(){
            div.className="change";
        }
    </script>
</body>
</html>

密码框验证信息

验证输入密码是否输入字符是否长度满足6~16位,如果满足,则返回

否则,返回 

 代码实现:

<!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>密码框验证信息</title>
    <style>
        div{
            width: 600px;
            margin: 100px auto;
        }
        .message{
            display: inline-block;
            size: 12px;
            color: #999;
            background:url(./images/mess.png) no-repeat left center;
            padding-left: 20px;
        }
        .worng{
            color: red;
            background-image: url(./images/wrong.png);
        }
        .right{
            color: green;
            background-image: url(./images/right.png);
        }
    </style>
</head>
<body>
    <div class="register">
        <input type="password" class="ipt">
        <p class="message">请输入6~16位密码</p>
        <script>
            var ipt=document.querySelector('.ipt');
            var mag=document.querySelector('.message');
            ipt.onblur=function(){
                if(this.value.length<6||this.value.length>16){
                    mag.className='message worng';
                    mag.innerHTML="您输入的位数不对要求6~16位"
                }else{
                    mag.className='message right';
                    mag.innerHTML='您输入的正确';
                }
            }
        </script>
    </div>
</body>
</html>

下拉选择框 

效果如下:

 代码实现:

<!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>下拉选择框</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    li {
            list-style-type: none;
        }

        a {
            text-decoration: none;
            font-size: 14px;
        }

        .nav {
            margin: 100px;
        }
        .nav > li {
            position: relative;
            float: left;
            width: 80px;
            height: 41px;
            text-align: center;
            border: 1px solid chartreuse;
        }

        .nav li a {
            display: block;
            width: 100%;
            height: 100%;
            line-height: 41px;
            color: #333;
        }
        .nav > li > a:hover {
            background-color: #eee;
        }

        .nav ul {
            display: none;
            position: absolute;
            top: 41px;
            left: 0;
            width: 100%;
            border-left: 1px solid #FECC5B;
            border-right: 1px solid #FECC5B;
        }

        .nav ul li {
            border-bottom: 1px solid #FECC5B;
        }

        .nav ul li a:hover {
            background-color: #FFF5DA;
        }
</style>
<body>
    <ul class="nav">
        <li>
            <a href="#">菜单</a>
            <ul>
                <li>
                    <a href="#">私信</a>
                </li>
                <li>
                    <a href="#">评论</a>
                </li>
                <li>
                    <a href="#">@我</a>
                </li>
            </ul>
        </li>
    </ul>
    <script>
        var nav=document.querySelector('.nav');
        var lis=nav.children;
        lis[0].onmouseover=function(){
            this.children[1].style.display='block';
        }
        lis[0].onmouseout=function(){
            this.children[1].style.display='none';
        }
    </script>
</body>
</html>

这篇博客到这已经到末尾了,如果觉得写的好,大家可以关注一下,以后大家可以一起学习!相互进步,后面我也可能为大家更新前端知识或者其它计算相关技术,最后谢谢各位博客的支持,我们下期再见 

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值