Node.js 具有带有 stdout 属性的进程对象,它是连接到 stdout 的流。使用 process.stdout 属性,我们可以访问几个有用的属性和方法:columns、rows、cursorTo 和 write。这些是在终端中启动“动画”某些内容的必需条件。
想象一下,我们想要为一个从屏幕上到下下落的“角色”制作动画,这可能是《黑客帝国》电影中“数字雨”动画的一小部分。
为此,我们需要几个步骤:
const column = 0 const character = '$' /* Pause for 1 second (1000 ms) */ const pause = () => new Promise((resolve) => setTimeout(resolve, 1000)) const main = async () => { /* Clear screen */ console.clear() /* Hide cursor */ process.stderr.write('\x1B[?25l') /* The number of rows */ const rows = process.stdout.rows /* Starting from the first row on the top of the screen. * Going to the bottom of the screen `process.stdout.rows`. */ for (let row = 0; row < rows; row++) { /* Set cursor into position `cursorTo(x, y)` * and write a character */ process.stdout.cursorTo(column, row) process.stdout.write(character) /* Pause for 1 second */ await pause() /* Set cursor into position and clear the character * (write a space) */ process.stdout.cursorTo(column, row) process.stdout.write(' ') } /* Show cursor */ process.stderr.write('\x1B[?25h') } main()
您可以在这里使用此代码。
接下来,为我们的动画添加一些颜色会很不错。为此,我们可以使用出色的 Ansis 库。
让我们输出一些绿色的东西:
/* import Ansis library */ import { green } from 'ansis' const character = '$' /* Apply green color to our character */ const coloredCharacter = green`${character}` /* Write colored character to the terminal */ process.stdout.write(coloredCharacter)
或者更好地将颜色从深绿色设置为浅绿色:
import { rgb } from 'ansis' const column = 0 const character = '$' /* Pause for 1 second (1000 ms) */ const pause = () => new Promise((resolve) => setTimeout(resolve, 1000)) const main = async () => { /* Clear screen */ console.clear() /* Hide cursor */ process.stderr.write('\x1B[?25l') /* The number of rows */ const rows = process.stdout.rows /* Starting from the first row on the top of the screen. * Going to the bottom of the screen `process.stdout.rows`. */ for (let row = 0; row < rows; row++) { /* Use the `rgb` function to change color * from dark to light green */ const g = Math.floor((255 / rows) * row) const coloredCharacter = rgb(0, g, 0)`${character}` /* Set cursor into position `cursorTo(x, y)` * and write a character */ process.stdout.cursorTo(column, row) process.stdout.write(coloredCharacter) /* Pause for 1 second */ await pause() /* Set cursor into position and clear the character * (write a space) */ process.stdout.cursorTo(column, row) process.stdout.write(' ') } /* Show cursor */ process.stderr.write('\x1B[?25h') } main()
我们可以使用这些简单的想法和动画技术来创造一些有趣且看起来很酷的东西。 ?
使用 npx jmatrix 命令查看 Matrix 数字雨的运行情况,并查看 Github 上的源代码。
卢卡斯在 Unsplash 上拍摄的照片
请在评论中发表您的想法、问题和想法,按?按钮,祝黑客快乐! ??
以上是使用 Node.js 的终端动画的详细内容。更多信息请关注PHP中文网其他相关文章!