random-text-bg
Version:
Add randomly scattered, selectable text in the background of your web page.
56 lines (45 loc) • 2.18 kB
JavaScript
(function (global) {
function RandomTextBg(options = {}) {
const config = {
text: options.text || '',
color: options.color || 'rgba(0, 0, 0, 0.3)',
fontSize: options.fontSize || '2rem',
fontFamily: options.fontFamily || 'monospace',
zIndex: options.zIndex || -1,
randomizeRotation: options.randomizeRotation !== false,
maxWords: options.maxWords || 1000,
textSelectable: options.textSelectable || false,
target: options.target || document.body // default to <body>
};
const isBody = config.target === document.body;
const words = config.text.split(/\s+/).slice(0, config.maxWords);
const container = document.createElement('div');
container.style.position = 'absolute';
container.style.top = 0;
container.style.left = 0;
container.style.width = isBody ? '100vw' : '100%';
container.style.height = isBody ? '100vh' : '100%';
container.style.pointerEvents = !config.textSelectable ? 'none' : '';
container.style.zIndex = config.zIndex;
container.style.overflow = 'hidden';
config.target.style.position = config.target.style.position || 'relative';
words.forEach(word => {
const span = document.createElement('span');
span.textContent = word;
span.style.position = 'absolute';
span.style.fontSize = config.fontSize;
span.style.fontFamily = config.fontFamily;
span.style.color = config.color;
const unitheight = isBody ? 'vh' : '%';
const unitWidth = isBody ? 'vw' : '%';
span.style.top = Math.random() * 100 + unitheight;
span.style.left = Math.random() * 100 + unitWidth;
if (config.randomizeRotation) {
span.style.transform = `rotate(${Math.random() * 360}deg)`;
}
container.appendChild(span);
});
config.target.appendChild(container);
}
global.RandomTextBg = RandomTextBg;
})(window);