使用 JavaScript 制作《黑客帝国》特效
CMatrix - JavaScript 中的矩阵效应
我一直是《黑客帝国三部曲》系列电影的忠实粉丝。在本文中,我们将使用原生 JavaScript 实现以下来自《黑客帝国》系列的视觉效果。
这张 GIF 动图针对尺寸进行了优化,因此画质较差,而且有些卡顿。不过最终效果会很流畅。我们开始吧。
我们将在 HTML5 上渲染此视觉效果canvas
。在本文中,除了 之外,我们的页面上不需要任何其他元素canvas
。最初,我们可以为其指定任意有效的尺寸(宽度和高度),因为我们将在 JS 代码中设置画布的实际宽度和高度。并且,我们将为其指定一个 ID,以便从 JS 代码中轻松引用它。
<canvas width="500" height="200" id="canv" />
现在我们可以获取此 DOM 节点canvas
,并设置其宽度和高度以填充body
。我们还将获取此画布的 2D 绘图上下文。为了实现此效果,屏幕将为黑色,因此我们将通过绘制一个宽度和高度与画布相同的黑色矩形来将画布填充为黑色。
// Get the canvas node and the drawing context
const canvas = document.getElementById('canv');
const ctx = canvas.getContext('2d');
// set the width and height of the canvas
const w = canvas.width = document.body.offsetWidth;
const h = canvas.height = document.body.offsetHeight;
// draw a black rectangle of width and height same as that of the canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, w, h);
我们希望文本按列排列。每列宽度为 20px。在动画的每一帧中,我们将在每列末尾放置一个字符。初始时,每列的末尾(y 坐标)为 0。
const cols = Math.floor(w / 20) + 1;
const ypos = Array(cols).fill(0);
在每一帧中,我们需要在前一帧的上方渲染一个半透明的黑色矩形,这样前一帧渲染的字符看起来就会逐渐变暗。然后,我们需要在当前帧的每一列末尾渲染新的字符。
每列的 y 坐标都存储在ypos
数组中。我们希望在每一帧中随机重置一些列,使其从顶部重新开始,这样看起来就像不同高度的列从顶部落下一样。对于其余列,我们只需将其 y 坐标向下移动 20px,这样在下一帧中,当前字符下方就会出现一个新字符。
function matrix () {
// Draw a semitransparent black rectangle on top of previous drawing
ctx.fillStyle = '#0001';
ctx.fillRect(0, 0, w, h);
// Set color to green and font to 15pt monospace in the drawing context
ctx.fillStyle = '#0f0';
ctx.font = '15pt monospace';
// for each column put a random character at the end
ypos.forEach((y, ind) => {
// generate a random character
const text = String.fromCharCode(Math.random() * 128);
// x coordinate of the column, y coordinate is already given
const x = ind * 20;
// render the character at (x, y)
ctx.fillText(text, x, y);
// randomly reset the end of the column if it's at least 100px high
if (y > 100 + Math.random() * 10000) ypos[ind] = 0;
// otherwise just move the y coordinate for the column 20px down,
else ypos[ind] = y + 20;
});
}
// render the animation at 20 FPS.
setInterval(matrix, 50);
这就是我们在原生 JS 中渲染矩阵效果所需的全部内容。本文的代码如下图所示,供参考。
希望你喜欢这篇文章,并从中有所收获。你可以在gnsp.in
上了解更多关于我的信息。
谢谢阅读!
文章来源:https://dev.to/gnsp/making-the-matrix-effect-in-javascript-din