问题描述
我想在我的 Web 应用程序中使用这个很酷的矩阵背景,但它涵盖了我的所有元素(div、标题、段落等)。
我尝试用 css 解决这个问题,但它不起作用。 所以现在我被困住了,需要你的帮助。
这是我来自 CodePen 的代码:
const canvas = document.getElementById('canv');
const ctx = canvas.getContext('2d');
const w = canvas.width = document.body.offsetWidth;
const h = canvas.height = document.body.offsetHeight;
const cols = Math.floor(w / 20) + 1;
const ypos = Array(cols).fill(0);
ctx.fillStyle = '#000';
ctx.fillRect(0,w,h);
function matrix () {
ctx.fillStyle = '#0001';
ctx.fillRect(0,h);
ctx.fillStyle = '#0f0';
ctx.font = '15pt monospace';
ypos.forEach((y,ind) => {
const text = String.fromCharCode(Math.random() * 128);
const x = ind * 20;
ctx.fillText(text,x,y);
if (y > 100 + Math.random() * 10000) ypos[ind] = 0;
else ypos[ind] = y + 20;
});
}
setInterval(matrix,50);
body {
margin: 0;
height: 100vh;
width: 100vw;
}
.container{
background-color: white;
}
<canvas id='canv'>
<div class='container'>
<p>Some div with login in</p>
</div>
</canvas>
有办法解决吗?
感谢您的关注和帮助。
解决方法
这是一个可能的解决方案:
const canvas = document.getElementById('canv');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
let cols = Math.floor(window.innerWidth / 20) + 1;
let ypos = Array(cols).fill(0);
ctx.fillStyle = '#000';
ctx.fillRect(0,canvas.width,canvas.height);
function matrix () {
const w = window.innerWidth;
const h = window.innerHeight;
if (canvas.width !== w) {
canvas.width = w;
cols = Math.floor(window.innerWidth / 20) + 1;
ypos = Array(cols).fill(0);
}
if (canvas.height !== h) {
canvas.height = h;
}
ctx.fillStyle = '#0001';
ctx.fillRect(0,w,h);
ctx.fillStyle = '#0f0';
ctx.font = '15pt monospace';
ypos.forEach((y,ind) => {
const text = String.fromCharCode(Math.random() * 128);
const x = ind * 20;
ctx.fillText(text,x,y);
if (y > 100 + Math.random() * 10000) ypos[ind] = 0;
else ypos[ind] = y + 20;
});
}
setInterval(matrix,50);
body {
margin: 0;
background-color: #000;
}
.container {
background-color: rgba(255,255,0.85);
margin: 50px 10%;
padding: 3rem;
position: relative;
z-index: 1;
}
#canv {
position: fixed;
top: 0;
left: 0;
}
<canvas id='canv'></canvas>
<div class='container'>
<p>Some div with login in</p>
</div>
使用 .container
的 CSS 使其看起来像您想要的那样。不要移除 position
和 z-index
(需要它们才能将其保留在 <canvas>
之上)。
注意:将 .container
放在顶部所需的 CSS 相当简单,这不是我添加答案的原因。
原因是您的矩阵脚本没有响应。我对它做了一些小的修改,现在它会在视口大小改变时调整大小。
欢迎来到 SO。