提问人:tekkyprograms 提问时间:8/21/2023 最后编辑:Han Hantekkyprograms 更新时间:8/21/2023 访问量:29
展开浏览器选项卡时动画背景未调整大小
Animated background not resize when the expanding the browser tab
问:
我有一个网站的动画二进制雨背景,除了我展开选项卡(调整屏幕大小)外,它工作正常,但是,背景没有调整,扩展区域留空。我包含了一个事件侦听器函数,该函数应将画布大小调整为窗口的大小,但我不确定为什么它不起作用。下面是 JS 代码:
// Get a reference to the canvas element and its 2D rendering context
var canvas = document.getElementById("binary-rain-canvas");
var ctx = canvas.getContext("2d");
// Function to set the canvas size based on window dimensions
function setCanvasSize() {
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
}
// Initialize the canvas size
setCanvasSize();
// Define the characters to use for the rain and split them into an array
var binaryChars = "01";
binaryChars = binaryChars.split("");
// Set the font size for the raindrops
var fontSize = 20;
// Calculate the number of columns based on canvas width and font size
var numColumns = canvas.width / fontSize;
// Initialize an array to track the position of each raindrop
var dropPositions = [];
// Initialize the drop positions with an initial value of 1
for (var column = 0; column < numColumns; column++) {
dropPositions[column] = 1;
}
// Function to draw the binary rain animation
function drawBinaryRain() {
// Set the background color with some transparency
ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Set the color of the raindrops
ctx.fillStyle = "#01DFEF";
// Set the font for the raindrops
ctx.font = fontSize + "px courier new";
// Loop through each column and update the raindrop positions
for (var i = 0; i < dropPositions.length; i++) {
// Select a random binary character
var binaryChar = binaryChars[Math.floor(Math.random() * binaryChars.length)];
// Draw the binary character at the current position
ctx.fillText(binaryChar, i * fontSize, dropPositions[i] * fontSize);
// Check if the raindrop has reached the bottom and reset it randomly
if (dropPositions[i] * fontSize > canvas.height && Math.random() > 0.975) {
dropPositions[i] = 0;
}
// Increment the position for the next frame
dropPositions[i]++;
}
}
// Call the drawBinaryRain function repeatedly to create the animation
setInterval(drawBinaryRain, 120);
// Event listener to adjust canvas size when the window is resized
window.addEventListener("resize", setCanvasSize);
如果有帮助,以下是相应的 html 代码:
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Page</title>
</head>
<style>
body{
background: #1d1f20;
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
}
canvas{
display: block;
position: fixed;
top: 0;
left: 0;
}
</style>
<body>
<canvas id = "binary-rain-canvas"></canvas>
<script src="about.js"></script>
</body>
</html>
答: 暂无答案
评论
dropPositions