使用ts实现虚拟世界,创建ts项目,并编写ts代码,使用tsc编译后直接加载到html界面,实现类似黑客帝国中的流淌的代码界面的效果。
源码下载地址:点击下载
讲解视频
TS实战项目一:数字流界面项目创建
TS实战项目三:动画效果优化
TS实战项目二:黑客界面组件绘制
B站视频
TS实战项目一:数字流界面项目创建
TS实战项目三:动画效果优化
TS实战项目二:数字流界面组件实现
西瓜视频
https://www.bilibili.com/video/BV1za4y1k7tz/
https://www.ixigua.com/7327475844874994227
https://www.ixigua.com/7327849788131508790
创建paint创建每个单元格的具体信息,包括要展示的字符、大小、颜色等信息;创建col实现每一列的的内容,列中包含该列中具体的paint信息,可以进行流淌动画的执行及字符的更新等。
自动计算界面大小,动态调整列的数量及字符的尺寸,通过定时动画实现字符颜色的变动及流淌的效果。
.\node_modules.bin\tsc --init生成ts的项目配置文件,此处注意直接用vscode的powershell运行的时候会保存,请切换到cmd命令窗口执行命令:
抖创建完毕后需要对项目进行初始化配置:
添加lite-server的启动指令,在package.json中的scripts中添加项目启动指令:“start”: “lite-server”,添加后可以直接使用npm start进行启动,启动后会自动启动一个web服务器,并自动打开默认浏览器,切每次js、css或html文件变动之后会自动刷新网页:
将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 ''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文件:
<!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>
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;
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;
}
}
/**
* 界面中基本元素
*/
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{}的方式进行监听界面加载完毕的事件。