今天来分享一个炫酷的特效,正如标题所提到的,我们使用到了 canvas 元素,可以理解为是一张画布,有了画布之后,我们就要在画布上进行绘制,而 canvas 元素本身是不具备绘图能力的,所以我们要借助 JavaScript 来完成绘制工作。
HTML 的结构我们只需要一个 标签就够了
<canvas id="canvas">
测试兼容性
</canvas>
设置全局 CSS 样式,很简单,代码如下:
html,body{
margin:0px;padding:0px;
overflow:hidden;
}
获取浏览器屏幕并设置其宽高,设置一个包含 256 个空元素的数组,.join(“1”) 用 1 来把数组里的元素拼接为字符串,.split(“”) 过滤掉数组里的空元素
const canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
s = window.screen,
w = canvas.width = s.width,
h = canvas.height = s.height;
let words = Array(256).join("1").split("");
随后绘制矩形,设置填充的颜色及文本
setInterval( () => {
ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "#20af0e";
//数组元素的映射
words.map( (y,n) => {
//生成A-Z a-z之间的值
text = String.fromCharCode(Math.ceil(65 + Math.random() * 57))
x = n * 10;
ctx.fillText(text, x, y);
words[n] = (y > 758 + Math.random() * 484 )? 0 : y + 10;
});
},50);