在1024程序員節,整點有意思的東西很重要。今天分享一個程式碼不到100行超輕量的Chrome擴展:在任意網頁按 Alt+M,一鍵觸發“黑客帝國”風格的程式碼雨螢幕保護程式,裝X效果直接拉滿,下面直接上效果與源碼。
1024
├── manifest.json # 擴展的"身份證"
└── content.js # 核心程式碼雨邏輯
1024{
"manifest_version": 3,
"name": "1024",
"version": "1.0.0",
"description": "Press Alt+M to trigger Matrix rain effect",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}
]
}
// 防止重複注入
if (!window.matrixRainInjected) {
window.matrixRainInjected = true;
let isRaining = false;
let canvas, ctx, animationId;
// 監聽快捷鍵 Alt+M
document.addEventListener('keydown', (e) => {
if (e.altKey && e.key.toLowerCase() === 'm') {
e.preventDefault();
toggleMatrixRain();
}
});
function toggleMatrixRain() {
if (isRaining) {
stopRain();
} else {
startRain();
}
}
function startRain() {
isRaining = true;
// 創建全屏Canvas
canvas = document.createElement('canvas');
canvas.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 999999;
pointer-events: none;
background: rgba(0, 0, 0, 0.9);
`;
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 簡化字元集
const chars = 'CODE1024';
const charArray = chars.split('');
const fontSize = 16;
const columns = Math.floor(canvas.width / fontSize);
const drops = Array(columns).fill(1);
// 動畫循環
function draw() {
// 半透明黑色背景,產生拖尾效果
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#0F0'; // 綠色字體
ctx.font = fontSize + 'px monospace';
for (let i = 0; i < drops.length; i++) {
// 隨機字元
const text = charArray[Math.floor(Math.random() * charArray.length)];
const x = i * fontSize;
const y = drops[i] * fontSize;
ctx.fillText(text, x, y);
// 隨機重置或繼續下落
if (y > canvas.height && Math.random() > 0.975) {
drops[i] = 0;
}
drops[i]++;
}
animationId = requestAnimationFrame(draw);
}
draw();
// 添加提示文字
setTimeout(() => {
const hint = document.createElement('div');
hint.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #0F0;
font-size: 24px;
font-family: monospace;
z-index: 9999999;
text-shadow: 0 0 10px #0F0;
pointer-events: none;
animation: fadeOut 3s forwards;
`;
hint.textContent = '[ Alt+M to exit ]';
// 添加淡出動畫
const style = document.createElement('style');
style.textContent = `
@keyframes fadeOut {
0% { opacity: 1; }
70% { opacity: 1; }
100% { opacity: 0; }
}
`;
document.head.appendChild(style);
document.body.appendChild(hint);
setTimeout(() => hint.remove(), 3000);
}, 500);
}
function stopRain() {
isRaining = false;
if (animationId) {
cancelAnimationFrame(animationId);
}
if (canvas) {
canvas.remove();
}
}
// 視窗大小改變時重新調整
window.addEventListener('resize', () => {
if (isRaining && canvas) {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
});
}
這個小玩具,祝各位程式員1024節快樂。
如果覺得對您有幫助,歡迎點讚 👍 收藏 ⭐ 追蹤 🔔 支持一下!
往期實戰推薦: