[ REFACT ] : FuzzyText Text Animation

This commit is contained in:
Utkarsh-Singhal-26
2026-02-01 13:47:32 +05:30
parent 7d1e9b0075
commit dbcaa6f488
3 changed files with 314 additions and 224 deletions

View File

@@ -1,17 +1,18 @@
import code from '@content/TextAnimations/FuzzyText/FuzzyText.vue?raw';
import { createCodeObject } from '@/types/code';
import code from '@content/TextAnimations/FuzzyText/FuzzyText.vue?raw';
export const fuzzyText = createCodeObject(code, 'TextAnimations/FuzzyText', {
usage: `<template>
<FuzzyText
text="404"
:font-size="140"
font-weight="900"
:font-weight="900"
color="#fff"
:enable-hover="true"
:base-intensity="0.18"
:hover-intensity="0.5"
/>
>
404
</FuzzyText>
</template>
<script setup lang="ts">

View File

@@ -1,8 +1,7 @@
<script setup lang="ts">
import { onMounted, onUnmounted, watch, nextTick, useTemplateRef } from 'vue';
import { computed, onBeforeUnmount, onMounted, useSlots, useTemplateRef, watch } from 'vue';
interface FuzzyTextProps {
text: string;
fontSize?: number | string;
fontWeight?: string | number;
fontFamily?: string;
@@ -10,78 +9,52 @@ interface FuzzyTextProps {
enableHover?: boolean;
baseIntensity?: number;
hoverIntensity?: number;
fuzzRange?: number;
fps?: number;
direction?: 'horizontal' | 'vertical' | 'both';
transitionDuration?: number;
clickEffect?: boolean;
glitchMode?: boolean;
glitchInterval?: number;
glitchDuration?: number;
gradient?: string[] | null;
letterSpacing?: number;
className?: string;
}
const props = withDefaults(defineProps<FuzzyTextProps>(), {
text: '',
fontSize: 'clamp(2rem, 8vw, 8rem)',
fontWeight: 900,
fontFamily: 'inherit',
color: '#fff',
enableHover: true,
baseIntensity: 0.18,
hoverIntensity: 0.5
hoverIntensity: 0.5,
fuzzRange: 30,
fps: 60,
direction: 'horizontal',
transitionDuration: 0,
clickEffect: false,
glitchMode: false,
glitchInterval: 2000,
glitchDuration: 200,
gradient: null,
letterSpacing: 0,
className: ''
});
const canvasRef = useTemplateRef<HTMLCanvasElement>('canvasRef');
const canvasRef = useTemplateRef<HTMLCanvasElement & { cleanupFuzzyText?: () => void }>('canvasRef');
const slots = useSlots();
let animationFrameId: number;
let isCancelled = false;
let cleanup: (() => void) | null = null;
let glitchTimeoutId: ReturnType<typeof setTimeout>;
let glitchEndTimeoutId: ReturnType<typeof setTimeout>;
let clickTimeoutId: ReturnType<typeof setTimeout>;
let cancelled = false;
const waitForFont = async (fontFamily: string, fontWeight: string | number, fontSize: string): Promise<boolean> => {
if (document.fonts?.check) {
const fontString = `${fontWeight} ${fontSize} ${fontFamily}`;
if (document.fonts.check(fontString)) {
return true;
}
try {
await document.fonts.load(fontString);
return document.fonts.check(fontString);
} catch (error) {
console.warn('Font loading failed:', error);
return false;
}
}
return new Promise(resolve => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
resolve(false);
return;
}
ctx.font = `${fontWeight} ${fontSize} ${fontFamily}`;
const testWidth = ctx.measureText('M').width;
let attempts = 0;
const checkFont = () => {
ctx.font = `${fontWeight} ${fontSize} ${fontFamily}`;
const newWidth = ctx.measureText('M').width;
if (newWidth !== testWidth && newWidth > 0) {
resolve(true);
} else if (attempts < 20) {
attempts++;
setTimeout(checkFont, 50);
} else {
resolve(false);
}
};
setTimeout(checkFont, 10);
});
};
const initCanvas = async () => {
if (document.fonts?.ready) {
await document.fonts.ready;
}
if (isCancelled) return;
const text = computed(() => (slots.default?.() ?? []).map(v => v.children).join(''));
const init = async () => {
const canvas = canvasRef.value;
if (!canvas) return;
@@ -92,184 +65,185 @@ const initCanvas = async () => {
props.fontFamily === 'inherit' ? window.getComputedStyle(canvas).fontFamily || 'sans-serif' : props.fontFamily;
const fontSizeStr = typeof props.fontSize === 'number' ? `${props.fontSize}px` : props.fontSize;
let numericFontSize: number;
const fontString = `${props.fontWeight} ${fontSizeStr} ${computedFontFamily}`;
try {
await document.fonts.load(fontString);
} catch {
await document.fonts.ready;
}
if (cancelled) return;
let numericFontSize: number;
if (typeof props.fontSize === 'number') {
numericFontSize = props.fontSize;
} else {
const temp = document.createElement('span');
temp.style.fontSize = props.fontSize;
temp.style.fontFamily = computedFontFamily;
document.body.appendChild(temp);
const computedSize = window.getComputedStyle(temp).fontSize;
numericFontSize = parseFloat(computedSize);
numericFontSize = parseFloat(getComputedStyle(temp).fontSize);
document.body.removeChild(temp);
}
const fontLoaded = await waitForFont(computedFontFamily, props.fontWeight, fontSizeStr);
if (!fontLoaded) {
console.warn(`Font not loaded: ${computedFontFamily}`);
}
const text = props.text;
const offscreen = document.createElement('canvas');
const offCtx = offscreen.getContext('2d');
if (!offCtx) return;
const fontString = `${props.fontWeight} ${fontSizeStr} ${computedFontFamily}`;
const offCtx = offscreen.getContext('2d')!;
offCtx.font = fontString;
offCtx.textBaseline = 'alphabetic';
const testMetrics = offCtx.measureText('M');
if (testMetrics.width === 0) {
setTimeout(() => {
if (!isCancelled) {
initCanvas();
}
}, 100);
return;
let totalWidth = 0;
if (props.letterSpacing !== 0) {
for (const char of text.value) {
totalWidth += offCtx.measureText(char).width + props.letterSpacing;
}
totalWidth -= props.letterSpacing;
} else {
totalWidth = offCtx.measureText(text.value).width;
}
const metrics = offCtx.measureText(text.value);
const ascent = metrics.actualBoundingBoxAscent ?? numericFontSize;
const descent = metrics.actualBoundingBoxDescent ?? numericFontSize * 0.2;
const height = Math.ceil(ascent + descent);
offscreen.width = Math.ceil(totalWidth) + 20;
offscreen.height = height;
offCtx.font = fontString;
offCtx.textBaseline = 'alphabetic';
const metrics = offCtx.measureText(text);
const actualLeft = metrics.actualBoundingBoxLeft ?? 0;
const actualRight = metrics.actualBoundingBoxRight ?? metrics.width;
const actualAscent = metrics.actualBoundingBoxAscent ?? numericFontSize;
const actualDescent = metrics.actualBoundingBoxDescent ?? numericFontSize * 0.2;
if (props.gradient && props.gradient.length >= 2) {
const grad = offCtx.createLinearGradient(0, 0, offscreen.width, 0);
props.gradient.forEach((c, i) => grad.addColorStop(i / (props.gradient!.length - 1), c));
offCtx.fillStyle = grad;
} else {
offCtx.fillStyle = props.color;
}
const textBoundingWidth = Math.ceil(actualLeft + actualRight);
const tightHeight = Math.ceil(actualAscent + actualDescent);
let x = 10;
for (const char of text.value) {
offCtx.fillText(char, x, ascent);
x += offCtx.measureText(char).width + props.letterSpacing;
}
const extraWidthBuffer = 10;
const offscreenWidth = textBoundingWidth + extraWidthBuffer;
const marginX = props.fuzzRange + 20;
const marginY = props.direction === 'vertical' || props.direction === 'both' ? props.fuzzRange + 10 : 0;
offscreen.width = offscreenWidth;
offscreen.height = tightHeight;
const xOffset = extraWidthBuffer / 2;
offCtx.font = `${props.fontWeight} ${fontSizeStr} ${computedFontFamily}`;
offCtx.textBaseline = 'alphabetic';
offCtx.fillStyle = props.color;
offCtx.fillText(text, xOffset - actualLeft, actualAscent);
const horizontalMargin = 50;
const verticalMargin = 0;
canvas.width = offscreenWidth + horizontalMargin * 2;
canvas.height = tightHeight + verticalMargin * 2;
ctx.translate(horizontalMargin, verticalMargin);
const interactiveLeft = horizontalMargin + xOffset;
const interactiveTop = verticalMargin;
const interactiveRight = interactiveLeft + textBoundingWidth;
const interactiveBottom = interactiveTop + tightHeight;
canvas.width = offscreen.width + marginX * 2;
canvas.height = offscreen.height + marginY * 2;
ctx.translate(marginX, marginY);
let isHovering = false;
const fuzzRange = 30;
let isClicking = false;
let isGlitching = false;
let currentIntensity = props.baseIntensity;
let targetIntensity = props.baseIntensity;
let lastFrameTime = 0;
const frameDuration = 1000 / props.fps;
const run = () => {
if (isCancelled) return;
ctx.clearRect(-fuzzRange, -fuzzRange, offscreenWidth + 2 * fuzzRange, tightHeight + 2 * fuzzRange);
const intensity = isHovering ? props.hoverIntensity : props.baseIntensity;
for (let j = 0; j < tightHeight; j++) {
const dx = Math.floor(intensity * (Math.random() - 0.5) * fuzzRange);
ctx.drawImage(offscreen, 0, j, offscreenWidth, 1, dx, j, offscreenWidth, 1);
const startGlitch = () => {
if (!props.glitchMode || cancelled) return;
glitchTimeoutId = setTimeout(() => {
isGlitching = true;
glitchEndTimeoutId = setTimeout(() => {
isGlitching = false;
startGlitch();
}, props.glitchDuration);
}, props.glitchInterval);
};
if (props.glitchMode) startGlitch();
const run = (ts: number) => {
if (cancelled) return;
if (ts - lastFrameTime < frameDuration) {
animationFrameId = requestAnimationFrame(run);
return;
}
animationFrameId = window.requestAnimationFrame(run);
lastFrameTime = ts;
ctx.clearRect(-marginX, -marginY, offscreen.width + marginX * 2, offscreen.height + marginY * 2);
targetIntensity = isClicking || isGlitching ? 1 : isHovering ? props.hoverIntensity : props.baseIntensity;
if (props.transitionDuration > 0) {
const step = 1 / (props.transitionDuration / frameDuration);
currentIntensity += Math.sign(targetIntensity - currentIntensity) * step;
currentIntensity = Math.min(
Math.max(currentIntensity, Math.min(targetIntensity, currentIntensity)),
Math.max(targetIntensity, currentIntensity)
);
} else {
currentIntensity = targetIntensity;
}
for (let y = 0; y < offscreen.height; y++) {
const dx = props.direction !== 'vertical' ? (Math.random() - 0.5) * currentIntensity * props.fuzzRange : 0;
const dy =
props.direction !== 'horizontal' ? (Math.random() - 0.5) * currentIntensity * props.fuzzRange * 0.5 : 0;
ctx.drawImage(offscreen, 0, y, offscreen.width, 1, dx, y + dy, offscreen.width, 1);
}
animationFrameId = requestAnimationFrame(run);
};
run();
animationFrameId = requestAnimationFrame(run);
const isInsideTextArea = (x: number, y: number) =>
x >= interactiveLeft && x <= interactiveRight && y >= interactiveTop && y <= interactiveBottom;
const rectCheck = (x: number, y: number) =>
x >= marginX && x <= marginX + offscreen.width && y >= marginY && y <= marginY + offscreen.height;
const handleMouseMove = (e: MouseEvent) => {
const mouseMove = (e: MouseEvent) => {
if (!props.enableHover) return;
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
isHovering = isInsideTextArea(x, y);
isHovering = rectCheck(e.clientX - rect.left, e.clientY - rect.top);
};
const handleMouseLeave = () => {
isHovering = false;
};
const mouseLeave = () => (isHovering = false);
const handleTouchMove = (e: TouchEvent) => {
if (!props.enableHover) return;
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const touch = e.touches[0];
const x = touch.clientX - rect.left;
const y = touch.clientY - rect.top;
isHovering = isInsideTextArea(x, y);
};
const handleTouchEnd = () => {
isHovering = false;
const click = () => {
if (!props.clickEffect) return;
isClicking = true;
clearTimeout(clickTimeoutId);
clickTimeoutId = setTimeout(() => (isClicking = false), 150);
};
if (props.enableHover) {
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseleave', handleMouseLeave);
canvas.addEventListener('touchmove', handleTouchMove, { passive: false });
canvas.addEventListener('touchend', handleTouchEnd);
canvas.addEventListener('mousemove', mouseMove);
canvas.addEventListener('mouseleave', mouseLeave);
}
cleanup = () => {
window.cancelAnimationFrame(animationFrameId);
if (props.enableHover) {
canvas.removeEventListener('mousemove', handleMouseMove);
canvas.removeEventListener('mouseleave', handleMouseLeave);
canvas.removeEventListener('touchmove', handleTouchMove);
canvas.removeEventListener('touchend', handleTouchEnd);
}
};
if (props.clickEffect) {
canvas.addEventListener('click', click);
}
onBeforeUnmount(() => {
cancelled = true;
cancelAnimationFrame(animationFrameId);
clearTimeout(glitchTimeoutId);
clearTimeout(glitchEndTimeoutId);
clearTimeout(clickTimeoutId);
canvas.removeEventListener('mousemove', mouseMove);
canvas.removeEventListener('mouseleave', mouseLeave);
canvas.removeEventListener('click', click);
});
};
onMounted(() => {
nextTick(() => {
initCanvas();
});
});
onUnmounted(() => {
isCancelled = true;
if (animationFrameId) {
window.cancelAnimationFrame(animationFrameId);
}
if (cleanup) {
cleanup();
}
});
onMounted(init);
watch(
[
() => props.text,
() => props.fontSize,
() => props.fontWeight,
() => props.fontFamily,
() => props.color,
() => props.enableHover,
() => props.baseIntensity,
() => props.hoverIntensity
],
() => ({ ...props, text: text.value }),
() => {
isCancelled = true;
if (animationFrameId) {
window.cancelAnimationFrame(animationFrameId);
}
if (cleanup) {
cleanup();
}
isCancelled = false;
nextTick(() => {
initCanvas();
});
cancelled = true;
cancelAnimationFrame(animationFrameId);
cancelled = false;
init();
}
);
</script>
<template>
<canvas ref="canvasRef" />
<canvas ref="canvasRef" :class="className" />
</template>

View File

@@ -1,37 +1,74 @@
<template>
<TabbedLayout>
<template #preview>
<div class="demo-container h-[500px] overflow-hidden">
<div class="flex flex-col items-center justify-center h-full">
<div class="h-[500px] overflow-hidden demo-container">
<div class="flex flex-col justify-center items-center h-full">
<FuzzyText
:key="`main-${rerenderKey}`"
text="404"
:base-intensity="baseIntensity"
:hover-intensity="hoverIntensity"
:enable-hover="enableHover"
:fuzz-range="fuzzRange"
:fps="fps"
:direction="direction"
:transition-duration="transitionDuration"
:click-effect="clickEffect"
:glitch-mode="glitchMode"
:glitch-interval="glitchInterval"
:glitch-duration="glitchDuration"
:letter-spacing="letterSpacing"
:font-size="140"
/>
>
404
</FuzzyText>
<div class="my-1" />
<FuzzyText
:key="`sub-${rerenderKey}`"
text="not found"
:base-intensity="baseIntensity"
:hover-intensity="hoverIntensity"
:enable-hover="enableHover"
:fuzz-range="fuzzRange"
:fps="fps"
:direction="direction"
:transition-duration="transitionDuration"
:click-effect="clickEffect"
:glitch-mode="glitchMode"
:glitch-interval="glitchInterval"
:glitch-duration="glitchDuration"
:letter-spacing="letterSpacing"
:font-size="70"
font-family="Gochi Hand"
/>
>
not found
</FuzzyText>
</div>
</div>
<Customize>
<PreviewSlider title="Base Intensity" v-model="baseIntensity" :min="0" :max="1" :step="0.01" />
<PreviewSlider title="Hover Intensity" v-model="hoverIntensity" :min="0" :max="2" :step="0.01" />
<PreviewSlider title="Fuzz Range" v-model="fuzzRange" :min="5" :max="100" :step="1" />
<PreviewSlider title="FPS" v-model="fps" :min="10" :max="120" :step="5" />
<PreviewSlider title="Transition Duration" v-model="transitionDuration" :min="0" :max="60" :step="1" />
<PreviewSlider title="Letter Spacing" v-model="letterSpacing" :min="-10" :max="50" :step="1" />
<PreviewSelect title="Direction" v-model="direction" :options="directionOptions" />
<PreviewSwitch title="Enable Hover" v-model="enableHover" />
<PreviewSwitch title="Click Effect" v-model="clickEffect" />
<PreviewSwitch title="Glitch Mode" v-model="glitchMode" />
<PreviewSlider
title="Glitch Interval"
v-model="glitchInterval"
:min="500"
:max="5000"
:step="100"
:disabled="!glitchMode"
/>
<PreviewSlider
title="Glitch Duration"
v-model="glitchDuration"
:min="50"
:max="1000"
:step="50"
:disabled="!glitchMode"
/>
</Customize>
<PropTable :data="propData" />
@@ -48,35 +85,47 @@
</template>
<script setup lang="ts">
import { ref } from 'vue';
import TabbedLayout from '../../components/common/TabbedLayout.vue';
import PropTable from '../../components/common/PropTable.vue';
import CliInstallation from '../../components/code/CliInstallation.vue';
import CodeExample from '../../components/code/CodeExample.vue';
import Customize from '../../components/common/Customize.vue';
import PreviewSlider from '../../components/common/PreviewSlider.vue';
import PreviewSwitch from '../../components/common/PreviewSwitch.vue';
import FuzzyText from '../../content/TextAnimations/FuzzyText/FuzzyText.vue';
import CliInstallation from '@/components/code/CliInstallation.vue';
import CodeExample from '@/components/code/CodeExample.vue';
import Customize from '@/components/common/Customize.vue';
import PreviewSlider from '@/components/common/PreviewSlider.vue';
import PreviewSwitch from '@/components/common/PreviewSwitch.vue';
import PropTable from '@/components/common/PropTable.vue';
import TabbedLayout from '@/components/common/TabbedLayout.vue';
import { fuzzyText } from '@/constants/code/TextAnimations/fuzzyTextCode';
import { useForceRerender } from '@/composables/useForceRerender';
import FuzzyText from '@/content/TextAnimations/FuzzyText/FuzzyText.vue';
import { ref } from 'vue';
const baseIntensity = ref(0.2);
const hoverIntensity = ref(0.5);
const enableHover = ref(true);
const fuzzRange = ref(30);
const fps = ref(60);
const direction = ref<'horizontal' | 'vertical' | 'both'>('horizontal');
const transitionDuration = ref(0);
const clickEffect = ref(false);
const glitchMode = ref(false);
const glitchInterval = ref(2000);
const glitchDuration = ref(200);
const letterSpacing = ref(0);
const { rerenderKey } = useForceRerender();
const directionOptions = [
{ value: 'horizontal', label: 'Horizontal' },
{ value: 'vertical', label: 'Vertical' },
{ value: 'both', label: 'Both' }
];
const propData = [
{
name: 'text',
name: 'slot',
type: 'string',
default: '""',
default: '',
description: 'The text content to display inside the fuzzy text component.'
},
{
name: 'fontSize',
type: 'number | string',
default: '"clamp(2rem, 8vw, 8rem)"',
default: `"clamp(2rem, 8vw, 8rem)"`,
description:
'Specifies the font size of the text. Accepts any valid CSS font-size value or a number (interpreted as pixels).'
},
@@ -89,8 +138,8 @@ const propData = [
{
name: 'fontFamily',
type: 'string',
default: '"inherit"',
description: 'Specifies the font family of the text. "inherit" uses the computed style from the parent.'
default: `"inherit"`,
description: "Specifies the font family of the text. 'inherit' uses the computed style from the parent."
},
{
name: 'color',
@@ -115,6 +164,72 @@ const propData = [
type: 'number',
default: '0.5',
description: 'The fuzz intensity when the text is hovered.'
},
{
name: 'fuzzRange',
type: 'number',
default: '30',
description: 'Maximum pixel displacement for the fuzzy effect.'
},
{
name: 'fps',
type: 'number',
default: '60',
description: 'Frame rate cap for the animation. Lower values reduce CPU usage.'
},
{
name: 'direction',
type: `'horizontal' | 'vertical' | 'both'`,
default: `'horizontal'`,
description: 'The axis/axes for the fuzzy displacement effect.'
},
{
name: 'transitionDuration',
type: 'number',
default: '0',
description: 'Number of frames to ease between intensity states for smooth transitions.'
},
{
name: 'clickEffect',
type: 'boolean',
default: 'false',
description: 'Enables a momentary burst of maximum intensity on click.'
},
{
name: 'glitchMode',
type: 'boolean',
default: 'false',
description: 'Enables periodic random intensity spikes for a glitch effect.'
},
{
name: 'glitchInterval',
type: 'number',
default: '2000',
description: 'Milliseconds between glitch bursts when glitchMode is enabled.'
},
{
name: 'glitchDuration',
type: 'number',
default: '200',
description: 'Milliseconds duration of each glitch burst.'
},
{
name: 'gradient',
type: 'string[] | null',
default: 'null',
description: 'Array of colors to create a gradient text effect (e.g. ["#ff0000", "#00ff00"]).'
},
{
name: 'letterSpacing',
type: 'number',
default: '0',
description: 'Extra pixels between characters.'
},
{
name: 'className',
type: 'string',
default: `''`,
description: 'CSS class for the canvas element.'
}
];
</script>