TS项目实战一:流淌的字符动画界面

  使用ts实现虚拟世界,创建ts项目,并编写ts代码,使用tsc编译后直接加载到html界面,实现类似黑客帝国中的流淌的代码界面的效果。
源码下载地址:点击下载

  1. 讲解视频

    TS实战项目一:数字流界面项目创建


    TS实战项目三:动画效果优化

    )]

    TS实战项目二:黑客界面组件绘制

  2. B站视频

    TS实战项目一:数字流界面项目创建


    TS实战项目三:动画效果优化

    现)]

    TS实战项目二:数字流界面组件实现

  3. 西瓜视频
    https://www.bilibili.com/video/BV1za4y1k7tz/
    https://www.ixigua.com/7327475844874994227
    https://www.ixigua.com/7327849788131508790

一.预期效果

来自网络

二.知识点

  1. tsc编译
  2. tsconfig.json配置项
  3. 模块定义及导入导出
  4. 类定义
  5. 参数属性
  6. 存取器

三.实现思路

  创建paint创建每个单元格的具体信息,包括要展示的字符、大小、颜色等信息;创建col实现每一列的的内容,列中包含该列中具体的paint信息,可以进行流淌动画的执行及字符的更新等。
自动计算界面大小,动态调整列的数量及字符的尺寸,通过定时动画实现字符颜色的变动及流淌的效果。

四.创建项目

  1. 创建node项目,使用npm init命令,如下:
    在这里插入图片描述

  2. 安装ts库,npm install TypeScript --save:
    在这里插入图片描述

  3. .\node_modules.bin\tsc --init生成ts的项目配置文件,此处注意直接用vscode的powershell运行的时候会保存,请切换到cmd命令窗口执行命令:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  4. 安装lite-server库,npm install lite-server,用于提供web服务:
    在这里插入图片描述

    安装完毕后的目录结构如下:
    在这里插入图片描述

抖创建完毕后需要对项目进行初始化配置:

  1. 添加lite-server的启动指令,在package.json中的scripts中添加项目启动指令:“start”: “lite-server”,添加后可以直接使用npm start进行启动,启动后会自动启动一个web服务器,并自动打开默认浏览器,切每次js、css或html文件变动之后会自动刷新网页:
    在这里插入图片描述
    在这里插入图片描述

  2. 将tsconfig.json中的module指定为es6,baseUrl设置为’./’,rootDirs设置为[],inlineSourceMap设置为true,outDir设置为./dist,具体的明细如下:

{"compilerOptions": {/* Visit https://aka.ms/tsconfig to read more about this file *//* Projects */// "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */// "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */// "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */// "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */// "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */// "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. *//* Language and Environment */"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */// "jsx": "preserve",                                /* Specify what JSX code is generated. */// "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */// "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */// "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */// "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */// "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */// "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */// "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */// "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */// "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. *//* Modules */"module": "ES6", /* Specify what module code is generated. */// "rootDir": "./",                                  /* Specify the root folder within your source files. */// "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */"baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */// "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */"rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */// "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */// "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */// "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */// "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */// "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */// "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */// "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */// "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */// "resolveJsonModule": true,                        /* Enable importing .json files. */// "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */// "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. *//* JavaScript Support */// "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */// "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */// "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. *//* Emit */// "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */// "declarationMap": true,                           /* Create sourcemaps for d.ts files. */// "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */// "sourceMap": true, /* Create source map files for emitted JavaScript files. */"inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */// "outFile": "./index.js", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */"outDir": "./dist", /* Specify an output folder for all emitted files. */// "removeComments": true,                           /* Disable emitting comments. */// "noEmit": true,                                   /* Disable emitting files from a compilation. */// "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */// "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */// "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */// "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */// "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */// "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */// "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */// "newLine": "crlf",                                /* Set the newline character for emitting files. */// "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */// "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */// "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */// "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */// "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */// "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. *//* Interop Constraints */// "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */// "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */"allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */// "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. *//* Type Checking */"strict": true, /* Enable all strict type-checking options. */// "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */// "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */// "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */// "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */// "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */// "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */// "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */// "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */// "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */// "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */// "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */// "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */// "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */// "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */// "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */// "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */// "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */// "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. *//* Completeness */// "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */"skipLibCheck": true /* Skip type checking all .d.ts files. */},"files": ["./src/index.ts",]
}

3.新建src目录及dist目录,src目录中创建index.ts文件,根目录创建index.html文件:
在这里插入图片描述

五.编码实现

  1. index.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><link rel="icon" href="/favicon.ico"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>黑客帝国演示</title><style>html,body {width: 100%;height: 100%;margin: 0px;padding: 0px;background-color: black;}#app {width: 100%;height: 100%;color: #fff;display: flex;overflow: hidden;}.col {flex: 1;text-align: center;line-height: 30px;}.point {}</style>
</head><body><div id="app"></div><script type="module" src="/dist/index.js"></script><script></script>
</body></html>
  1. index.ts
import Col from './col';
/*** 入口文件,控制字符的内容*/
import Point from './point';//列的数量
let colCount: number = 0;
//字符的大小
let charSize: number = 30;
//颜色
let sizes: number[] = [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
//颜色
let colors = ['#00ffd2ef', '#00fb6744', '#00d55777', '#00d50888', '#00ff0a33', '#3efb0266'];
//生成数据
let cols: Array<Col> = new Array<Col>();
//字符集
let chars: string[] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', ',', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '~', '!', '@', '#', '$', '%', '^', '&', '*', '"', '.', '/', '+', '-'];/*** 动态效果*/
const animina = () => {cols.forEach(col => {for (let i = col.points.length - 1; i > 0; i--) {col.points[i].char = col.points[i - 1].char;col.points[i].div.innerText = col.points[i].char;let color = colors[parseInt((Math.random() * 10) + '') % colors.length];col.points[i].color = color;col.points[i].div.style.color = color;let size = sizes[parseInt((Math.random() * 20) + '') % sizes.length];col.points[i].size = size;col.points[i].div.style.fontSize = col.points[i].size + 'ox';}let char = chars[parseInt((Math.random() * 100) + '') % chars.length];col.points[0].char = char;col.points[0].div.innerText = col.points[0].char;let color = colors[parseInt((Math.random() * 10) + '') % colors.length];col.points[0].color = color;col.points[0].div.style.color = color;let size = sizes[parseInt((Math.random() * 20) + '') % sizes.length];col.points[0].size = size;col.points[0].div.style.fontSize = col.points[0].size + 'ox';})window.requestAnimationFrame(animina);
}/*** 初始化界面*/
const init = () => {//计算列数colCount = window.screen.availWidth / (charSize + 8);//生成组件for (let i = 0; i < colCount; i++) {let points: Array<Point> = new Array<Point>();let div: HTMLElement = document.createElement('div');div.className = "col";for (let j = 0; j < 50; j++) {let pointdiv: HTMLElement = document.createElement('div');pointdiv.className = "point";let char = chars[parseInt((Math.random() * 100) + '') % chars.length];let color = colors[parseInt((Math.random() * 10) + '') % colors.length];let size = sizes[parseInt((Math.random() * 20) + '') % sizes.length];let point: Point = new Point(char, size, color, pointdiv);pointdiv.innerText = point.char;pointdiv.style.fontSize = point.size + 'px';// pointdiv.style.fontWeight = '600';pointdiv.style.color = point.color;points.push(point);}let col: Col = new Col(points, div);cols.push(col);}//绘制到界面上let root: HTMLElement | null = document.getElementById('app');root?.remove();root = document.createElement('div');root.id = 'app';document.body.appendChild(root);cols.forEach(col => {col.points.forEach(point => {let pointdiv = point.div;col.div.appendChild(pointdiv);})root?.append(col.div);})window.requestAnimationFrame(animina);
}//将内容挂在到界面
window.onload = function (event: any) {init();
}
export default init;
  1. col.ts
import Point from './point';/*** 每一列展示的内容*/
export default class Col {constructor(private _points: Array<Point>, private _div: HTMLElement) {}set points(points: Array<Point>) {this._points = points;}get points(): Array<Point> {return this._points;}set div(points: HTMLElement) {this._div = points;}get div(): HTMLElement {return this._div;}
}
  1. point.ts
/*** 界面中基本元素*/
export default class Point {/*** 构造函数* @param char  字符* @param size 大小* @param color 颜色*/constructor(private _char: string, private _size: number, private _color: string, private _div: HTMLElement) { }set char(char: string) {this._char = char;}get char(): string {return this._char;}set size(size: number) {this._size = size;}get size(): number {return this._size;}set color(color: string) {this._color = color;}get color(): string {return this._color;}set div(div: HTMLElement) {this._div = div;}get div(): HTMLElement {return this._div;}
}

六.效果预览

在这里插入图片描述

七.遇到的问题

问题一: 项目创建后无法加载到html界面,需要指定编译输出为es6才可以,使用其它的模块加载器,需要引入对应的模块加载器环境。

问题二: ts中引入的import Point from ‘./Point’,在js中未自动添加.js后缀,导致界面加载时找不到paint文件,加载失败,需要手动将编译后js文件中的import 语句中添加上.js后缀。

问题三: 使用window.onload(()=>{})时报错,传入的回调函数的类型不匹配,因为有可能回调的时候this时null,需要直接使用window.onload = function():any{}的方式进行监听界面加载完毕的事件。

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

聚道云软件连接器助力金融科技公司,提升企业管理效率

客户介绍 某金融服务控股有限公司&#xff0c;是中国领先的金融科技公司&#xff0c;专注于为金融机构提供智能风控、智能营销、智能客服、智能运营等产品和服务。公司拥有强大的技术研发实力&#xff0c;在人工智能、大数据、云计算等领域拥有多项核心技术专利。 客户痛点 在…

抽象类(Java)、模板方法设计模式

一、概念 在Java中有abstract关键字&#xff0c;就是抽象的意思&#xff0c;可用来修饰类和成员方法。 用abstract来修饰类&#xff0c;那这个类就是抽象类&#xff1b;修饰方法&#xff0c;那这个方法就是抽象方法。 修饰符 abstract class 类名{修饰符 abstract 返回值类型…

力扣题目训练(6)

2024年1月30日力扣题目训练 2024年1月30日力扣题目训练367. 有效的完全平方数374. 猜数字大小383. 赎金信99. 恢复二叉搜索树105. 从前序与中序遍历序列构造二叉树51. N 皇后 2024年1月30日力扣题目训练 2024年1月30日第六天编程训练&#xff0c;今天主要是进行一些题训练&…

分库分表已成为过去式,使用分布式数据库才是未来

当我们使用 Mysql数据库到达一定量级以后&#xff0c;性能就会逐步下降&#xff0c;而解决此类问题&#xff0c;常用的手段就是引入数据库中间件进行分库分表处理&#xff0c;比如使用 Mycat、ShadingShpere、tddl&#xff0c;但是这种都是过去式了&#xff0c;现在使用分布式数…

STM32——感应开关盖垃圾桶

STM32——感应开关盖垃圾桶 1.定时器介绍 软件定时 缺点&#xff1a;不精确、占用CPU资源 void Delay500ms() //11.0592MHz {unsigned char i, j, k;_nop_();i 4;j 129;k 119;do{do{while (--k);} while (--j);} while (--i); }定时器工作原理 使用精准的时基&#xff…

【C语言】整数和浮点数在内存中的存储

前言 我们都知道&#xff0c;在创建一个变量的时候&#xff0c;编译器会自动开辟一块内存空间用于存放它&#xff0c;但是对于不同的数据类型&#xff0c;它们的存储形式也会有所不同。今天就让我们一起来学习整数和浮点数在内存中的存储 1. 整数在内存中的存储 我们都知道&…

leetcode刷题(剑指offer) 10.正则表达式匹配

10.正则表达式匹配 给你一个字符串 s 和一个字符规律 p&#xff0c;请你来实现一个支持 . 和 * 的正则表达式匹配。 . 匹配任意单个字符* 匹配零个或多个前面的那一个元素 所谓匹配&#xff0c;是要涵盖 整个 字符串 s的&#xff0c;而不是部分字符串。 示例 1&#xff1a;…

Linus Torvalds的20个事实

Linus Torvalds 是 Linux 操作系统的创造者&#xff0c;至今还在维护内核。本文是他的自传《Just for fun》的简短摘录&#xff0c;关于他个人的20个事实&#xff0c;比如他的老婆是他的学生。 Brief: Some known, some lesser known – here are 20 facts about the Linus Tor…

外汇天眼:Cryptodfmeta与Aden Markets──网恋对象热心带投资,鼓吹加码冻账拒出金

随着整个人类社会进入数字时代&#xff0c;我们愈来愈仰赖网络科技的便利性&#xff0c;由于远端工作逐渐成为趋势&#xff0c;就连社交与人际互动也开始云端化。 与此同时&#xff0c;诈骗集团也在各大社交平台申请假账号并寻找下手目标&#xff0c;并且诱骗人使用虚假的投资平…

JSON概述以及使用

1&#xff0c;JSON 1.1 概述 概念&#xff1a;JavaScript Object Notation。JavaScript 对象表示法. 如下是 JavaScript 对象的定义格式&#xff1a; {name:"zhangsan",age:23,city:"北京" } 接下来我们再看看 JSON 的格式&#xff1a; {"name&…

C++文件操作(1)

C文件操作 1.文本的写入及读取文本文件写入文本文件读取 2.二进制文件的写入及读取二进制文件写入二进制文件读取 3.小结 C也有处理文件的能力&#xff0c;其功能实现依赖文件流。文件流是C中用来处理文件输入输出的一种流类。文件流可以用于从文件中读取数据或将数据写入到文件…

uni-app小程序自定义导航栏

最近在开发一个uni-app小程序&#xff0c;用到了自定义导航栏&#xff0c;在这里记录一下实现过程&#xff1a; page.json 在对应页面路由的style中设置入"navigationStyle": "custom"取消原生导航栏&#xff0c;自定义导航栏 {"path": "…