Pixel Trail
Grid sel kecil yang menyala di bawah kursor lalu memudar, digambar di satu canvas. Fokus keyboard menyalakan sel di sekitar elemen yang difokus.
Interfaces that answer the pointer
Move across the grid and leave a trail.
Interfaces that answer the pointer
Move across the grid and leave a trail.
Interfaces that answer the pointer
Move across the grid and leave a trail.
Interfaces that answer the pointer
Move across the grid and leave a trail.
Interfaces that answer the pointer
Move across the grid and leave a trail.
@php
$hero = 'grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center';
$title = 'max-w-72 text-2xl font-semibold text-ink';
$text = 'text-sm text-muted';
@endphp
<x-markas.pixel-trail show-grid :class="$hero">
<h3 class="{{ $title }}">Interfaces that answer the pointer</h3>
<p class="{{ $text }}">Move across the grid and leave a trail.</p>
<x-markas.button>Get started</x-markas.button>
</x-markas.pixel-trail>import { Button } from "@/components/markas/Button";
import { PixelTrail } from "@/components/markas/PixelTrail";
const hero =
"grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center";
const title = "max-w-72 text-2xl font-semibold text-ink";
const text = "text-sm text-muted";
export default function PixelTrailExample() {
return (
<PixelTrail showGrid className={hero}>
<h3 className={title}>Interfaces that answer the pointer</h3>
<p className={text}>Move across the grid and leave a trail.</p>
<Button>Get started</Button>
</PixelTrail>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import PixelTrail from "@/components/markas/PixelTrail.vue";
const hero =
"grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center";
const title = "max-w-72 text-2xl font-semibold text-ink";
const text = "text-sm text-muted";
</script>
<template>
<PixelTrail show-grid :class="hero">
<h3 :class="title">Interfaces that answer the pointer</h3>
<p :class="text">Move across the grid and leave a trail.</p>
<Button>Get started</Button>
</PixelTrail>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import PixelTrail from "$lib/components/markas/PixelTrail.svelte";
const hero =
"grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center";
const title = "max-w-72 text-2xl font-semibold text-ink";
const text = "text-sm text-muted";
</script>
<PixelTrail showGrid class={hero}>
<h3 class={title}>Interfaces that answer the pointer</h3>
<p class={text}>Move across the grid and leave a trail.</p>
<Button>Get started</Button>
</PixelTrail>---
import Button from "@/components/markas/Button.astro";
import PixelTrail from "@/components/markas/PixelTrail.astro";
const hero =
"grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center";
const title = "max-w-72 text-2xl font-semibold text-ink";
const text = "text-sm text-muted";
---
<PixelTrail showGrid class={hero}>
<h3 class={title}>Interfaces that answer the pointer</h3>
<p class={text}>Move across the grid and leave a trail.</p>
<Button>Get started</Button>
</PixelTrail>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { PixelTrail } from "./markas/pixel-trail.component";
@Component({
selector: "markas-example",
imports: [Button, PixelTrail],
template: `
<markas-pixel-trail showGrid [class]="hero">
<h3 [class]="title">Interfaces that answer the pointer</h3>
<p [class]="text">Move across the grid and leave a trail.</p>
<button markas-button>Get started</button>
</markas-pixel-trail>
`,
})
export default class PixelTrailExample {
protected readonly hero =
"grid h-72 content-center justify-items-center gap-3 rounded-xl border border-line bg-surface p-6 text-center";
protected readonly title = "max-w-72 text-2xl font-semibold text-ink";
protected readonly text = "text-sm text-muted";
}Contoh
Kartu ajakan dengan titik
Join 4,000 teams across Indonesia
Free for 14 days, then from Rp 49.000 a month.
Join 4,000 teams across Indonesia
Free for 14 days, then from Rp 49.000 a month.
Join 4,000 teams across Indonesia
Free for 14 days, then from Rp 49.000 a month.
Join 4,000 teams across Indonesia
Free for 14 days, then from Rp 49.000 a month.
Join 4,000 teams across Indonesia
Free for 14 days, then from Rp 49.000 a month.
@php
$card = 'grid gap-4 rounded-xl border border-line bg-subtle p-6';
$title = 'text-xl font-semibold text-ink';
$text = 'mt-1 text-sm text-muted';
$actions = 'flex flex-wrap gap-3';
@endphp
<x-markas.pixel-trail variant="dot" color="success" :cell-size="16" :fade="900" :class="$card">
<div>
<h3 class="{{ $title }}">Join 4,000 teams across Indonesia</h3>
<p class="{{ $text }}">Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div class="{{ $actions }}">
<x-markas.button>Start free trial</x-markas.button>
<x-markas.button variant="secondary">Talk to sales</x-markas.button>
</div>
</x-markas.pixel-trail>import { Button } from "@/components/markas/Button";
import { PixelTrail } from "@/components/markas/PixelTrail";
const card = "grid gap-4 rounded-xl border border-line bg-subtle p-6";
const title = "text-xl font-semibold text-ink";
const text = "mt-1 text-sm text-muted";
const actions = "flex flex-wrap gap-3";
export default function Example() {
return (
<PixelTrail
variant="dot"
color="success"
cellSize={16}
fade={900}
className={card}
>
<div>
<h3 className={title}>Join 4,000 teams across Indonesia</h3>
<p className={text}>Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div className={actions}>
<Button>Start free trial</Button>
<Button variant="secondary">Talk to sales</Button>
</div>
</PixelTrail>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import PixelTrail from "@/components/markas/PixelTrail.vue";
const card = "grid gap-4 rounded-xl border border-line bg-subtle p-6";
const title = "text-xl font-semibold text-ink";
const text = "mt-1 text-sm text-muted";
const actions = "flex flex-wrap gap-3";
</script>
<template>
<PixelTrail
variant="dot"
color="success"
:cell-size="16"
:fade="900"
:class="card"
>
<div>
<h3 :class="title">Join 4,000 teams across Indonesia</h3>
<p :class="text">Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div :class="actions">
<Button>Start free trial</Button>
<Button variant="secondary">Talk to sales</Button>
</div>
</PixelTrail>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import PixelTrail from "$lib/components/markas/PixelTrail.svelte";
const card = "grid gap-4 rounded-xl border border-line bg-subtle p-6";
const title = "text-xl font-semibold text-ink";
const text = "mt-1 text-sm text-muted";
const actions = "flex flex-wrap gap-3";
</script>
<PixelTrail variant="dot" color="success" cellSize={16} fade={900} class={card}>
<div>
<h3 class={title}>Join 4,000 teams across Indonesia</h3>
<p class={text}>Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div class={actions}>
<Button>Start free trial</Button>
<Button variant="secondary">Talk to sales</Button>
</div>
</PixelTrail>---
import Button from "@/components/markas/Button.astro";
import PixelTrail from "@/components/markas/PixelTrail.astro";
const card = "grid gap-4 rounded-xl border border-line bg-subtle p-6";
const title = "text-xl font-semibold text-ink";
const text = "mt-1 text-sm text-muted";
const actions = "flex flex-wrap gap-3";
---
<PixelTrail variant="dot" color="success" cellSize={16} fade={900} class={card}>
<div>
<h3 class={title}>Join 4,000 teams across Indonesia</h3>
<p class={text}>Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div class={actions}>
<Button>Start free trial</Button>
<Button variant="secondary">Talk to sales</Button>
</div>
</PixelTrail>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { PixelTrail } from "./markas/pixel-trail.component";
@Component({
selector: "markas-example",
imports: [Button, PixelTrail],
template: `
<markas-pixel-trail
variant="dot"
color="success"
[cellSize]="16"
[fade]="900"
[class]="card"
>
<div>
<h3 [class]="title">Join 4,000 teams across Indonesia</h3>
<p [class]="text">Free for 14 days, then from Rp 49.000 a month.</p>
</div>
<div [class]="actions">
<button markas-button>Start free trial</button>
<button markas-button variant="secondary">Talk to sales</button>
</div>
</markas-pixel-trail>
`,
})
export default class PixelTrailCtaExample {
protected readonly card =
"grid gap-4 rounded-xl border border-line bg-subtle p-6";
protected readonly title = "text-xl font-semibold text-ink";
protected readonly text = "mt-1 text-sm text-muted";
protected readonly actions = "flex flex-wrap gap-3";
}Area coret dengan kuas lembut
Sketch pad
Draw with your cursor. It doodles on its own too.
Sketch pad
Draw with your cursor. It doodles on its own too.
Sketch pad
Draw with your cursor. It doodles on its own too.
Sketch pad
Draw with your cursor. It doodles on its own too.
Sketch pad
Draw with your cursor. It doodles on its own too.
@php
$pad = 'grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4';
$title = 'text-sm font-semibold text-ink';
$text = 'text-sm text-muted';
@endphp
<x-markas.pixel-trail variant="brush" color="warning" :cell-size="12" :fade="1500" autoplay :class="$pad">
<p class="{{ $title }}">Sketch pad</p>
<p class="{{ $text }}">Draw with your cursor. It doodles on its own too.</p>
</x-markas.pixel-trail>import { PixelTrail } from "@/components/markas/PixelTrail";
const pad =
"grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4";
const title = "text-sm font-semibold text-ink";
const text = "text-sm text-muted";
export default function Example() {
return (
<PixelTrail
variant="brush"
color="warning"
cellSize={12}
fade={1500}
autoplay
className={pad}
>
<p className={title}>Sketch pad</p>
<p className={text}>Draw with your cursor. It doodles on its own too.</p>
</PixelTrail>
);
}<script setup lang="ts">
import PixelTrail from "@/components/markas/PixelTrail.vue";
const pad =
"grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4";
const title = "text-sm font-semibold text-ink";
const text = "text-sm text-muted";
</script>
<template>
<PixelTrail
variant="brush"
color="warning"
:cell-size="12"
:fade="1500"
autoplay
:class="pad"
>
<p :class="title">Sketch pad</p>
<p :class="text">Draw with your cursor. It doodles on its own too.</p>
</PixelTrail>
</template><script lang="ts">
import PixelTrail from "$lib/components/markas/PixelTrail.svelte";
const pad =
"grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4";
const title = "text-sm font-semibold text-ink";
const text = "text-sm text-muted";
</script>
<PixelTrail
variant="brush"
color="warning"
cellSize={12}
fade={1500}
autoplay
class={pad}
>
<p class={title}>Sketch pad</p>
<p class={text}>Draw with your cursor. It doodles on its own too.</p>
</PixelTrail>---
import PixelTrail from "@/components/markas/PixelTrail.astro";
const pad =
"grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4";
const title = "text-sm font-semibold text-ink";
const text = "text-sm text-muted";
---
<PixelTrail variant="brush" color="warning" cellSize={12} fade={1500} autoplay class={pad}>
<p class={title}>Sketch pad</p>
<p class={text}>Draw with your cursor. It doodles on its own too.</p>
</PixelTrail>import { Component } from "@angular/core";
import { PixelTrail } from "./markas/pixel-trail.component";
@Component({
selector: "markas-example",
imports: [PixelTrail],
template: `
<markas-pixel-trail
variant="brush"
color="warning"
[cellSize]="12"
[fade]="1500"
autoplay
[class]="pad"
>
<p [class]="title">Sketch pad</p>
<p [class]="text">Draw with your cursor. It doodles on its own too.</p>
</markas-pixel-trail>
`,
})
export default class PixelTrailSketchExample {
protected readonly pad =
"grid h-64 content-end rounded-xl border border-dashed border-line bg-canvas p-4";
protected readonly title = "text-sm font-semibold text-ink";
protected readonly text = "text-sm text-muted";
}Strip navbar dengan cahaya fokus
@php
$bar = 'flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4';
$brand = 'text-base font-semibold text-ink';
$links = 'flex gap-4 text-sm text-muted';
$link = 'rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
$pages = [
['label' => 'Docs', 'href' => '/docs'],
['label' => 'Components', 'href' => '/components'],
['label' => 'Templates', 'href' => '/templates'],
];
@endphp
<x-markas.pixel-trail color="ink" :cell-size="8" :fade="400" :class="$bar">
<span class="{{ $brand }}">Markas</span>
<nav aria-label="Main">
<ul class="{{ $links }}">
@foreach ($pages as $page)
<li><a href="{{ $page['href'] }}" class="{{ $link }}">{{ $page['label'] }}</a></li>
@endforeach
</ul>
</nav>
<x-markas.button size="sm">Sign in</x-markas.button>
</x-markas.pixel-trail>import { Button } from "@/components/markas/Button";
import { PixelTrail } from "@/components/markas/PixelTrail";
const bar =
"flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4";
const brand = "text-base font-semibold text-ink";
const links = "flex gap-4 text-sm text-muted";
const link =
"rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const pages = [
{ label: "Docs", href: "/docs" },
{ label: "Components", href: "/components" },
{ label: "Templates", href: "/templates" },
];
export default function Example() {
return (
<PixelTrail color="ink" cellSize={8} fade={400} className={bar}>
<span className={brand}>Markas</span>
<nav aria-label="Main">
<ul className={links}>
{pages.map((page) => (
<li key={page.label}>
<a href={page.href} className={link}>
{page.label}
</a>
</li>
))}
</ul>
</nav>
<Button size="sm">Sign in</Button>
</PixelTrail>
);
}<script setup lang="ts">
import Button from "@/components/markas/Button.vue";
import PixelTrail from "@/components/markas/PixelTrail.vue";
const bar =
"flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4";
const brand = "text-base font-semibold text-ink";
const links = "flex gap-4 text-sm text-muted";
const link =
"rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const pages = [
{ label: "Docs", href: "/docs" },
{ label: "Components", href: "/components" },
{ label: "Templates", href: "/templates" },
];
</script>
<template>
<PixelTrail color="ink" :cell-size="8" :fade="400" :class="bar">
<span :class="brand">Markas</span>
<nav aria-label="Main">
<ul :class="links">
<li v-for="page in pages" :key="page.label">
<a :href="page.href" :class="link">{{ page.label }}</a>
</li>
</ul>
</nav>
<Button size="sm">Sign in</Button>
</PixelTrail>
</template><script lang="ts">
import Button from "$lib/components/markas/Button.svelte";
import PixelTrail from "$lib/components/markas/PixelTrail.svelte";
const bar =
"flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4";
const brand = "text-base font-semibold text-ink";
const links = "flex gap-4 text-sm text-muted";
const link =
"rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const pages = [
{ label: "Docs", href: "/docs" },
{ label: "Components", href: "/components" },
{ label: "Templates", href: "/templates" },
];
</script>
<PixelTrail color="ink" cellSize={8} fade={400} class={bar}>
<span class={brand}>Markas</span>
<nav aria-label="Main">
<ul class={links}>
{#each pages as page (page.label)}<li>
<a href={page.href} class={link}>{page.label}</a>
</li>{/each}
</ul>
</nav>
<Button size="sm">Sign in</Button>
</PixelTrail>---
import Button from "@/components/markas/Button.astro";
import PixelTrail from "@/components/markas/PixelTrail.astro";
const bar =
"flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4";
const brand = "text-base font-semibold text-ink";
const links = "flex gap-4 text-sm text-muted";
const link =
"rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const pages = [
{ label: "Docs", href: "/docs" },
{ label: "Components", href: "/components" },
{ label: "Templates", href: "/templates" },
];
---
<PixelTrail color="ink" cellSize={8} fade={400} class={bar}>
<span class={brand}>Markas</span>
<nav aria-label="Main">
<ul class={links}>
{pages.map((page) => (<li>
<a href={page.href} class={link}>{page.label}</a>
</li>))}
</ul>
</nav>
<Button size="sm">Sign in</Button>
</PixelTrail>import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { PixelTrail } from "./markas/pixel-trail.component";
@Component({
selector: "markas-example",
imports: [Button, PixelTrail],
template: `
<markas-pixel-trail color="ink" [cellSize]="8" [fade]="400" [class]="bar">
<span [class]="brand">Markas</span>
<nav aria-label="Main">
<ul [class]="links">
@for (page of pages; track page.label) {
<li>
<a [attr.href]="page.href" [class]="link">{{ page.label }}</a>
</li>
}
</ul>
</nav>
<button markas-button size="sm">Sign in</button>
</markas-pixel-trail>
`,
})
export default class PixelTrailNavbarExample {
protected readonly bar =
"flex h-16 items-center justify-between gap-4 rounded-xl border border-line bg-surface px-4";
protected readonly brand = "text-base font-semibold text-ink";
protected readonly links = "flex gap-4 text-sm text-muted";
protected readonly link =
"rounded-sm hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
protected readonly pages = [
{ label: "Docs", href: "/docs" },
{ label: "Components", href: "/components" },
{ label: "Templates", href: "/templates" },
];
}Instalasi
npx markasui@latest add pixel-trailpnpm dlx markasui@latest add pixel-trailyarn dlx markasui@latest add pixel-trailbunx --bun markasui@latest add pixel-trail- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Pasang dependensi:
npm install alpinejs - Salin source komponen di bawah ini ke
resources/views/components/markas/pixel-trail.blade.php.
@props([
'cellSize' => 24,
'fade' => 600,
'variant' => 'pixel',
'color' => 'primary',
'showGrid' => false,
'autoplay' => false,
])
@php
$base = 'relative isolate overflow-hidden';
$canvasClass = 'pointer-events-none absolute inset-0 -z-10 size-full';
$gridClass = 'bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]';
$colors = [
'primary' => 'text-primary',
'success' => 'text-success',
'warning' => 'text-warning',
'danger' => 'text-danger',
'ink' => 'text-ink',
];
$options = [
'size' => (float) $cellSize,
'fade' => (float) $fade,
'variant' => in_array($variant, ['pixel', 'dot', 'brush'], true) ? $variant : 'pixel',
'autoplay' => (bool) $autoplay,
];
@endphp
{{-- Lights the cell under the pointer on a canvas and fades it over `fade` ms. Keyboard focus lights the cells around the focused element. --}}
<div
x-data="{
stop: null,
init() {
const { size, fade, variant, autoplay } = @js($options);
const root = this.$root;
const canvas = this.$refs.canvas;
const context = canvas.getContext?.('2d');
if (! context || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
const lit = new Map();
let last = null;
let frame = 0;
let color = '';
let inside = false;
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col, row] = key.split(',').map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === 'dot') context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col, row, strength = 1) => {
const key = `${col},${row}`;
const current = lit.get(key);
if (! current || current.strength * 0.8 <= strength) lit.set(key, { time: performance.now(), strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x, y) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== 'brush') return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
{{-- Paint every half cell between the last point and this one, so fast moves leave no gaps. --}}
const trail = (x, y) => {
const from = last ?? { x, y };
const steps = Math.max(1, Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)));
for (let i = 1; i <= steps; i++) paint(from.x + ((x - from.x) * i) / steps, from.y + ((y - from.y) * i) / steps);
last = { x, y };
};
const move = (event) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event) => {
const target = event.target;
if (target === root || ! target.matches?.(':focus-visible')) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom) light(col, row, 0.8);
};
resize();
const resizer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null;
resizer?.observe(canvas);
root.addEventListener('pointermove', move);
root.addEventListener('pointerleave', leave);
root.addEventListener('focusin', focus);
{{-- Autoplay: a trail of its own while visible, the tab is shown, and the pointer is elsewhere. --}}
let auto = 0;
let observer = null;
let sync = null;
if (autoplay && typeof IntersectionObserver === 'function') {
let seen = false;
const run = (now) => {
if (! inside) {
const t = now / 1000;
trail(canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)), canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)));
}
auto = requestAnimationFrame(run);
};
sync = () => {
cancelAnimationFrame(auto);
if (seen && ! document.hidden) auto = requestAnimationFrame(run);
};
observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(root);
document.addEventListener('visibilitychange', sync);
}
this.stop = () => {
resizer?.disconnect();
observer?.disconnect();
if (sync) document.removeEventListener('visibilitychange', sync);
root.removeEventListener('pointermove', move);
root.removeEventListener('pointerleave', leave);
root.removeEventListener('focusin', focus);
cancelAnimationFrame(auto);
cancelAnimationFrame(frame);
};
},
destroy() {
this.stop?.();
},
}"
{{ $attributes->merge(['style' => '--cell: '.(float) $cellSize.'px'])->class([$base]) }}
>
<canvas x-ref="canvas" wire:ignore aria-hidden="true" @class([$canvasClass, $colors[$color] ?? $colors['primary'], $gridClass => $showGrid])></canvas>
{{ $slot }}
</div>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/PixelTrail.tsx.
"use client";
import { useEffect, useRef, type ComponentProps } from "react";
export type PixelTrailVariant = "pixel" | "dot" | "brush";
const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
"bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
primary: "text-primary",
success: "text-success",
warning: "text-warning",
danger: "text-danger",
ink: "text-ink",
};
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const still = () =>
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
type TrailOptions = {
size: number;
fade: number;
variant: PixelTrailVariant;
autoplay: boolean;
};
/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
let frame = 0;
let seen = false;
const run = (now: number) => {
tick(now);
frame = requestAnimationFrame(run);
};
const sync = () => {
cancelAnimationFrame(frame);
if (seen && !document.hidden) frame = requestAnimationFrame(run);
};
const observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(element);
document.addEventListener("visibilitychange", sync);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
};
}
/**
* Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
* the cells around the focused element. The canvas only redraws while some cell is still lit.
*/
function createPixels(
root: HTMLElement,
canvas: HTMLCanvasElement,
options: TrailOptions,
) {
const { size, fade, variant } = options;
const context = canvas.getContext?.("2d");
if (!context || still()) return () => {};
const lit = new Map<string, { time: number; strength: number }>();
let last: { x: number; y: number } | null = null;
let frame = 0;
let color = "";
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now: number) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col = 0, row = 0] = key.split(",").map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === "dot")
context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col: number, row: number, strength = 1) => {
const key = `${col},${row}`;
const time = performance.now();
const current = lit.get(key);
if (!current || current.strength * 0.8 <= strength)
lit.set(key, { time, strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x: number, y: number) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== "brush") return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
/** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
const trail = (x: number, y: number) => {
const from = last ?? { x, y };
const steps = Math.max(
1,
Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
);
for (let i = 1; i <= steps; i++)
paint(
from.x + ((x - from.x) * i) / steps,
from.y + ((y - from.y) * i) / steps,
);
last = { x, y };
};
let inside = false;
const move = (event: PointerEvent) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
if (target === root || !target.matches?.(":focus-visible")) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom)
light(col, row, 0.8);
};
resize();
const observer =
typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
observer?.observe(canvas);
root.addEventListener("pointermove", move);
root.addEventListener("pointerleave", leave);
root.addEventListener("focusin", focus);
const stopAuto =
options.autoplay && typeof IntersectionObserver === "function"
? whileVisible(root, (now) => {
if (inside) return;
const t = now / 1000;
trail(
canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
);
})
: null;
return () => {
observer?.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerleave", leave);
root.removeEventListener("focusin", focus);
stopAuto?.();
cancelAnimationFrame(frame);
};
}
export type PixelTrailProps = ComponentProps<"div"> & {
/** Side of one cell in px. */
cellSize?: number;
/** How long a lit cell takes to fade out, in ms. */
fade?: number;
/** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
variant?: PixelTrailVariant;
/** Light color token. */
color?: keyof typeof colors;
/** Draws faint grid lines between the cells. */
showGrid?: boolean;
/** Draws a trail on its own while visible and the pointer is elsewhere. */
autoplay?: boolean;
};
export function PixelTrail({
cellSize = 24,
fade = 600,
variant = "pixel",
color = "primary",
showGrid = false,
autoplay = false,
className,
style,
children,
...props
}: PixelTrailProps) {
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(
() =>
createPixels(rootRef.current!, canvasRef.current!, {
size: cellSize,
fade,
variant,
autoplay,
}),
[cellSize, fade, variant, autoplay],
);
return (
<div
{...props}
ref={rootRef}
className={cx(base, className)}
style={
{
"--cell": `${cellSize}px`,
...style,
} as ComponentProps<"div">["style"]
}
>
<canvas
ref={canvasRef}
aria-hidden="true"
className={cx(canvasClass, colors[color], showGrid && gridClass)}
></canvas>
{children}
</div>
);
}- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/PixelTrail.vue.
<script setup lang="ts">
import { onBeforeUnmount, onMounted, useTemplateRef, watch } from "vue";
export type PixelTrailVariant = "pixel" | "dot" | "brush";
const colors = {
primary: "text-primary",
success: "text-success",
warning: "text-warning",
danger: "text-danger",
ink: "text-ink",
};
const props = withDefaults(
defineProps<{
/** Side of one cell in px. */
cellSize?: number;
/** How long a lit cell takes to fade out, in ms. */
fade?: number;
/** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
variant?: PixelTrailVariant;
/** Light color token. */
color?: keyof typeof colors;
/** Draws faint grid lines between the cells. */
showGrid?: boolean;
/** Draws a trail on its own while visible and the pointer is elsewhere. */
autoplay?: boolean;
}>(),
{
cellSize: 24,
fade: 600,
variant: "pixel",
color: "primary",
showGrid: false,
autoplay: false,
},
);
const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
"bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const still = () =>
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
let frame = 0;
let seen = false;
const run = (now: number) => {
tick(now);
frame = requestAnimationFrame(run);
};
const sync = () => {
cancelAnimationFrame(frame);
if (seen && !document.hidden) frame = requestAnimationFrame(run);
};
const observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(element);
document.addEventListener("visibilitychange", sync);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
};
}
/**
* Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
* the cells around the focused element. The canvas only redraws while some cell is still lit.
*/
function createPixels(root: HTMLElement, canvas: HTMLCanvasElement) {
const { cellSize: size, fade, variant } = props;
const context = canvas.getContext?.("2d");
if (!context || still()) return () => {};
const lit = new Map<string, { time: number; strength: number }>();
let last: { x: number; y: number } | null = null;
let frame = 0;
let color = "";
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now: number) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col = 0, row = 0] = key.split(",").map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === "dot")
context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col: number, row: number, strength = 1) => {
const key = `${col},${row}`;
const time = performance.now();
const current = lit.get(key);
if (!current || current.strength * 0.8 <= strength)
lit.set(key, { time, strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x: number, y: number) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== "brush") return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
/** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
const trail = (x: number, y: number) => {
const from = last ?? { x, y };
const steps = Math.max(
1,
Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
);
for (let i = 1; i <= steps; i++)
paint(
from.x + ((x - from.x) * i) / steps,
from.y + ((y - from.y) * i) / steps,
);
last = { x, y };
};
let inside = false;
const move = (event: PointerEvent) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
if (target === root || !target.matches?.(":focus-visible")) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom)
light(col, row, 0.8);
};
resize();
const observer =
typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
observer?.observe(canvas);
root.addEventListener("pointermove", move);
root.addEventListener("pointerleave", leave);
root.addEventListener("focusin", focus);
const stopAuto =
props.autoplay && typeof IntersectionObserver === "function"
? whileVisible(root, (now) => {
if (inside) return;
const t = now / 1000;
trail(
canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
);
})
: null;
return () => {
observer?.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerleave", leave);
root.removeEventListener("focusin", focus);
stopAuto?.();
cancelAnimationFrame(frame);
};
}
const rootEl = useTemplateRef<HTMLDivElement>("rootRef");
const canvasEl = useTemplateRef<HTMLCanvasElement>("canvasRef");
let stop = () => {};
const start = () => {
stop();
stop = createPixels(rootEl.value!, canvasEl.value!);
};
onMounted(start);
watch(() => [props.cellSize, props.fade, props.variant, props.autoplay], start);
onBeforeUnmount(() => stop());
</script>
<template>
<div ref="rootRef" :class="base" :style="{ '--cell': `${props.cellSize}px` }">
<canvas
ref="canvasRef"
aria-hidden="true"
:class="[canvasClass, colors[props.color], props.showGrid && gridClass]"
></canvas>
<slot />
</div>
</template>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/lib/components/markas/PixelTrail.svelte.
<script lang="ts">
import type { Snippet } from "svelte";
import type { HTMLAttributes } from "svelte/elements";
type PixelTrailVariant = "pixel" | "dot" | "brush";
const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
"bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
primary: "text-primary",
success: "text-success",
warning: "text-warning",
danger: "text-danger",
ink: "text-ink",
};
const still = () =>
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
type TrailOptions = {
size: number;
fade: number;
variant: PixelTrailVariant;
autoplay: boolean;
};
/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
let frame = 0;
let seen = false;
const run = (now: number) => {
tick(now);
frame = requestAnimationFrame(run);
};
const sync = () => {
cancelAnimationFrame(frame);
if (seen && !document.hidden) frame = requestAnimationFrame(run);
};
const observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(element);
document.addEventListener("visibilitychange", sync);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
};
}
/**
* Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
* the cells around the focused element. The canvas only redraws while some cell is still lit.
*/
function createPixels(
root: HTMLElement,
canvas: HTMLCanvasElement,
options: TrailOptions,
) {
const { size, fade, variant } = options;
const context = canvas.getContext?.("2d");
if (!context || still()) return () => {};
const lit = new Map<string, { time: number; strength: number }>();
let last: { x: number; y: number } | null = null;
let frame = 0;
let color = "";
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now: number) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col = 0, row = 0] = key.split(",").map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === "dot")
context.arc(
(col + 0.5) * size,
(row + 0.5) * size,
size * 0.32,
0,
7,
);
else
context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col: number, row: number, strength = 1) => {
const key = `${col},${row}`;
const time = performance.now();
const current = lit.get(key);
if (!current || current.strength * 0.8 <= strength)
lit.set(key, { time, strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x: number, y: number) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== "brush") return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
/** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
const trail = (x: number, y: number) => {
const from = last ?? { x, y };
const steps = Math.max(
1,
Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
);
for (let i = 1; i <= steps; i++)
paint(
from.x + ((x - from.x) * i) / steps,
from.y + ((y - from.y) * i) / steps,
);
last = { x, y };
};
let inside = false;
const move = (event: PointerEvent) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
if (target === root || !target.matches?.(":focus-visible")) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom)
light(col, row, 0.8);
};
resize();
const observer =
typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
observer?.observe(canvas);
root.addEventListener("pointermove", move);
root.addEventListener("pointerleave", leave);
root.addEventListener("focusin", focus);
const stopAuto =
options.autoplay && typeof IntersectionObserver === "function"
? whileVisible(root, (now) => {
if (inside) return;
const t = now / 1000;
trail(
canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
);
})
: null;
return () => {
observer?.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerleave", leave);
root.removeEventListener("focusin", focus);
stopAuto?.();
cancelAnimationFrame(frame);
};
}
type Props = HTMLAttributes<HTMLDivElement> & {
/** Side of one cell in px. */
cellSize?: number;
/** How long a lit cell takes to fade out, in ms. */
fade?: number;
/** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
variant?: PixelTrailVariant;
/** Light color token. */
color?: keyof typeof colors;
/** Draws faint grid lines between the cells. */
showGrid?: boolean;
/** Draws a trail on its own while visible and the pointer is elsewhere. */
autoplay?: boolean;
children?: Snippet;
};
let {
cellSize = 24,
fade = 600,
variant = "pixel",
color = "primary",
showGrid = false,
autoplay = false,
class: className,
style,
children,
...rest
}: Props = $props();
let root = $state<HTMLDivElement>();
let canvas = $state<HTMLCanvasElement>();
$effect(() => {
const options = { size: cellSize, fade, variant, autoplay };
if (root && canvas) return createPixels(root, canvas, options);
});
</script>
<div
{...rest}
bind:this={root}
class={[base, className]}
style={`--cell: ${cellSize}px;${style ? ` ${style}` : ""}`}
>
<canvas
bind:this={canvas}
aria-hidden="true"
class={[canvasClass, colors[color], showGrid && gridClass]}
></canvas>
{@render children?.()}
</div>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/components/markas/PixelTrail.astro.
---
import type { HTMLAttributes } from "astro/types";
type PixelTrailVariant = "pixel" | "dot" | "brush";
const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
"bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
primary: "text-primary",
success: "text-success",
warning: "text-warning",
danger: "text-danger",
ink: "text-ink",
};
type Props = HTMLAttributes<"div"> & {
/** Side of one cell in px. */
cellSize?: number;
/** How long a lit cell takes to fade out, in ms. */
fade?: number;
/** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
variant?: PixelTrailVariant;
/** Light color token. */
color?: keyof typeof colors;
/** Draws faint grid lines between the cells. */
showGrid?: boolean;
/** Draws a trail on its own while visible and the pointer is elsewhere. */
autoplay?: boolean;
};
const {
cellSize = 24,
fade = 600,
variant = "pixel",
color = "primary",
showGrid = false,
autoplay = false,
class: className,
style,
...rest
} = Astro.props;
const options = JSON.stringify({
size: Number(cellSize),
fade: Number(fade),
variant,
autoplay: Boolean(autoplay),
});
const userStyle = typeof style === "string" && style ? ` ${style}` : "";
---
<markas-pixel-trail class="contents" data-options={options}>
<div
{...rest}
class:list={[base, className]}
style={`--cell: ${cellSize}px;${userStyle}`}
>
<canvas
aria-hidden="true"
class:list={[canvasClass, colors[color], showGrid && gridClass]}
></canvas>
<slot />
</div>
</markas-pixel-trail>
<script>
type PixelTrailVariant = "pixel" | "dot" | "brush";
const still = () =>
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
type TrailOptions = {
size: number;
fade: number;
variant: PixelTrailVariant;
autoplay: boolean;
};
/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
let frame = 0;
let seen = false;
const run = (now: number) => {
tick(now);
frame = requestAnimationFrame(run);
};
const sync = () => {
cancelAnimationFrame(frame);
if (seen && !document.hidden) frame = requestAnimationFrame(run);
};
const observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(element);
document.addEventListener("visibilitychange", sync);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
};
}
/**
* Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
* the cells around the focused element. The canvas only redraws while some cell is still lit.
*/
function createPixels(
root: HTMLElement,
canvas: HTMLCanvasElement,
options: TrailOptions,
) {
const { size, fade, variant } = options;
const context = canvas.getContext?.("2d");
if (!context || still()) return () => {};
const lit = new Map<string, { time: number; strength: number }>();
let last: { x: number; y: number } | null = null;
let frame = 0;
let color = "";
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now: number) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col = 0, row = 0] = key.split(",").map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === "dot")
context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col: number, row: number, strength = 1) => {
const key = `${col},${row}`;
const time = performance.now();
const current = lit.get(key);
if (!current || current.strength * 0.8 <= strength)
lit.set(key, { time, strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x: number, y: number) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== "brush") return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
/** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
const trail = (x: number, y: number) => {
const from = last ?? { x, y };
const steps = Math.max(
1,
Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
);
for (let i = 1; i <= steps; i++)
paint(
from.x + ((x - from.x) * i) / steps,
from.y + ((y - from.y) * i) / steps,
);
last = { x, y };
};
let inside = false;
const move = (event: PointerEvent) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
if (target === root || !target.matches?.(":focus-visible")) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom)
light(col, row, 0.8);
};
resize();
const observer =
typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
observer?.observe(canvas);
root.addEventListener("pointermove", move);
root.addEventListener("pointerleave", leave);
root.addEventListener("focusin", focus);
const stopAuto =
options.autoplay && typeof IntersectionObserver === "function"
? whileVisible(root, (now) => {
if (inside) return;
const t = now / 1000;
trail(
canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
);
})
: null;
return () => {
observer?.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerleave", leave);
root.removeEventListener("focusin", focus);
stopAuto?.();
cancelAnimationFrame(frame);
};
}
// Per instance: each area owns its canvas, pointer trail, and autoplay loop.
class PixelTrail extends HTMLElement {
#stop = () => {};
connectedCallback() {
const root = this.firstElementChild as HTMLElement | null;
const canvas = root?.firstElementChild;
if (!root || !(canvas instanceof HTMLCanvasElement)) return;
this.#stop = createPixels(
root,
canvas,
JSON.parse(this.dataset.options ?? "{}") as TrailOptions,
);
}
disconnectedCallback() {
this.#stop();
}
}
if (!customElements.get("markas-pixel-trail"))
customElements.define("markas-pixel-trail", PixelTrail);
</script>- Pastikan Tailwind CSS v4 dan markas.css sudah terpasang. Lihat Instalasi.
- Salin source komponen di bawah ini ke
src/app/markas/pixel-trail.component.ts.
import {
afterRenderEffect,
booleanAttribute,
ChangeDetectionStrategy,
Component,
computed,
type ElementRef,
input,
numberAttribute,
viewChild,
} from "@angular/core";
export type PixelTrailVariant = "pixel" | "dot" | "brush";
const base = "relative isolate overflow-hidden";
const canvasClass = "pointer-events-none absolute inset-0 -z-10 size-full";
const gridClass =
"bg-[linear-gradient(var(--color-line)_1px,transparent_1px),linear-gradient(90deg,var(--color-line)_1px,transparent_1px)] bg-size-[var(--cell)_var(--cell)]";
const colors = {
primary: "text-primary",
success: "text-success",
warning: "text-warning",
danger: "text-danger",
ink: "text-ink",
};
const cx = (...c: (string | false | null | undefined)[]) =>
c.filter(Boolean).join(" ");
const still = () =>
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
type TrailOptions = {
size: number;
fade: number;
variant: PixelTrailVariant;
autoplay: boolean;
};
/** Run `tick` on every frame while the element is on screen and the tab is visible. */
function whileVisible(element: Element, tick: (now: number) => void) {
let frame = 0;
let seen = false;
const run = (now: number) => {
tick(now);
frame = requestAnimationFrame(run);
};
const sync = () => {
cancelAnimationFrame(frame);
if (seen && !document.hidden) frame = requestAnimationFrame(run);
};
const observer = new IntersectionObserver(([entry]) => {
seen = Boolean(entry?.isIntersecting);
sync();
});
observer.observe(element);
document.addEventListener("visibilitychange", sync);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", sync);
cancelAnimationFrame(frame);
};
}
/**
* Light the cell under the pointer on a canvas and fade it out over `fade` ms. Keyboard focus lights
* the cells around the focused element. The canvas only redraws while some cell is still lit.
*/
function createPixels(
root: HTMLElement,
canvas: HTMLCanvasElement,
options: TrailOptions,
) {
const { size, fade, variant } = options;
const context = canvas.getContext?.("2d");
if (!context || still()) return () => {};
const lit = new Map<string, { time: number; strength: number }>();
let last: { x: number; y: number } | null = null;
let frame = 0;
let color = "";
const resize = () => {
const ratio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * ratio;
canvas.height = canvas.clientHeight * ratio;
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const draw = (now: number) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
for (const [key, cell] of lit) {
const alpha = cell.strength * (1 - (now - cell.time) / fade);
if (alpha <= 0) {
lit.delete(key);
continue;
}
const [col = 0, row = 0] = key.split(",").map(Number);
context.globalAlpha = Math.min(alpha, 1);
context.beginPath();
if (variant === "dot")
context.arc((col + 0.5) * size, (row + 0.5) * size, size * 0.32, 0, 7);
else context.rect(col * size + 0.5, row * size + 0.5, size - 1, size - 1);
context.fill();
}
frame = lit.size ? requestAnimationFrame(draw) : 0;
};
const light = (col: number, row: number, strength = 1) => {
const key = `${col},${row}`;
const time = performance.now();
const current = lit.get(key);
if (!current || current.strength * 0.8 <= strength)
lit.set(key, { time, strength });
if (frame) return;
color = getComputedStyle(canvas).color;
frame = requestAnimationFrame(draw);
};
const paint = (x: number, y: number) => {
const col = Math.floor(x / size);
const row = Math.floor(y / size);
light(col, row);
if (variant !== "brush") return;
for (let dx = -2; dx <= 2; dx++)
for (let dy = -2; dy <= 2; dy++) {
const far = Math.max(Math.abs(dx), Math.abs(dy));
if (far) light(col + dx, row + dy, far === 1 ? 0.5 : 0.2);
}
};
/** Paint every half cell between the last point and this one, so fast moves leave no gaps. */
const trail = (x: number, y: number) => {
const from = last ?? { x, y };
const steps = Math.max(
1,
Math.ceil(Math.hypot(x - from.x, y - from.y) / (size / 2)),
);
for (let i = 1; i <= steps; i++)
paint(
from.x + ((x - from.x) * i) / steps,
from.y + ((y - from.y) * i) / steps,
);
last = { x, y };
};
let inside = false;
const move = (event: PointerEvent) => {
inside = true;
const rect = root.getBoundingClientRect();
trail(event.clientX - rect.left, event.clientY - rect.top);
};
const leave = () => {
inside = false;
last = null;
};
const focus = (event: FocusEvent) => {
const target = event.target as HTMLElement;
if (target === root || !target.matches?.(":focus-visible")) return;
const box = root.getBoundingClientRect();
const rect = target.getBoundingClientRect();
const left = Math.floor((rect.left - box.left) / size) - 1;
const top = Math.floor((rect.top - box.top) / size) - 1;
const right = Math.floor((rect.right - box.left) / size) + 1;
const bottom = Math.floor((rect.bottom - box.top) / size) + 1;
for (let col = left; col <= right; col++)
for (let row = top; row <= bottom; row++)
if (col === left || col === right || row === top || row === bottom)
light(col, row, 0.8);
};
resize();
const observer =
typeof ResizeObserver === "function" ? new ResizeObserver(resize) : null;
observer?.observe(canvas);
root.addEventListener("pointermove", move);
root.addEventListener("pointerleave", leave);
root.addEventListener("focusin", focus);
const stopAuto =
options.autoplay && typeof IntersectionObserver === "function"
? whileVisible(root, (now) => {
if (inside) return;
const t = now / 1000;
trail(
canvas.clientWidth * (0.5 + 0.42 * Math.sin(t * 1.3)),
canvas.clientHeight * (0.5 + 0.36 * Math.sin(t * 0.9 + 1)),
);
})
: null;
return () => {
observer?.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerleave", leave);
root.removeEventListener("focusin", focus);
stopAuto?.();
cancelAnimationFrame(frame);
};
}
export type PixelTrailColor = keyof typeof colors;
/** The host stays out of layout; the user's class lands on the area. */
@Component({
selector: "markas-pixel-trail",
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: "contents" },
template: `
<div #rootEl [class]="classes()" [style.--cell]="cellSize() + 'px'">
<canvas #canvasEl aria-hidden="true" [class]="canvasClasses()"></canvas>
<ng-content />
</div>
`,
})
export class PixelTrail {
/** Side of one cell in px. */
readonly cellSize = input(24, { transform: numberAttribute });
/** How long a lit cell takes to fade out, in ms. */
readonly fade = input(600, { transform: numberAttribute });
/** Shape of the light: square pixels, round dots, or a soft brush that also lights the neighbours. */
readonly variant = input<PixelTrailVariant>("pixel");
/** Light color token. */
readonly color = input<PixelTrailColor>("primary");
/** Draws faint grid lines between the cells. */
readonly showGrid = input(false, { transform: booleanAttribute });
/** Draws a trail on its own while visible and the pointer is elsewhere. */
readonly autoplay = input(false, { transform: booleanAttribute });
readonly userClass = input("", { alias: "class" });
protected readonly classes = computed(() => cx(base, this.userClass()));
protected readonly canvasClasses = computed(() =>
cx(canvasClass, colors[this.color()], this.showGrid() && gridClass),
);
private readonly root = viewChild.required<ElementRef<HTMLElement>>("rootEl");
private readonly canvas =
viewChild.required<ElementRef<HTMLCanvasElement>>("canvasEl");
constructor() {
afterRenderEffect((onCleanup) => {
const options = {
size: this.cellSize(),
fade: this.fade(),
variant: this.variant(),
autoplay: this.autoplay(),
};
onCleanup(
createPixels(
this.root().nativeElement,
this.canvas().nativeElement,
options,
),
);
});
}
}Pemakaian
<x-markas.pixel-trail variant="dot" color="success" :cell-size="16" :fade="900" show-grid class="grid h-80 place-items-center rounded-xl bg-surface">
<h1 class="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
</x-markas.pixel-trail>Butuh Alpine.js.
import { PixelTrail } from "@/components/markas/PixelTrail";
<PixelTrail
variant="dot"
color="success"
cellSize={16}
fade={900}
showGrid
className="grid h-80 place-items-center rounded-xl bg-surface"
>
<h1 className="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
</PixelTrail>;<template>
<PixelTrail
variant="dot"
color="success"
:cell-size="16"
:fade="900"
show-grid
class="grid h-80 place-items-center rounded-xl bg-surface"
>
<h1 class="text-4xl font-semibold">Pembayaran yang terasa instan</h1>
</PixelTrail>
</template><script lang="ts">
import PixelTrail from "$lib/components/markas/PixelTrail.svelte";
</script>
<PixelTrail
variant="dot"
showGrid
class="grid h-64 place-items-center rounded-xl"
>
<h2 class="text-2xl font-semibold">Move your mouse</h2>
</PixelTrail>---
import PixelTrail from "@/components/markas/PixelTrail.astro";
---
<PixelTrail variant="dot" showGrid class="grid h-64 place-items-center rounded-xl">
<h2 class="text-2xl font-semibold">Move your mouse</h2>
</PixelTrail>Satu script kecil yang dibundel menggambar setiap canvas lewat elemen markas-pixel-trail.
import { Component } from "@angular/core";
import { PixelTrail } from "./markas/pixel-trail.component";
@Component({
selector: "app-hero",
imports: [PixelTrail],
template: `
<markas-pixel-trail
variant="dot"
showGrid
class="grid h-64 place-items-center rounded-xl"
>
<h2 class="text-2xl font-semibold">Move your mouse</h2>
</markas-pixel-trail>
`,
})
export class Hero {}- Sel digambar di satu canvas di belakang konten, jadi ribuan sel pun tidak menambah node DOM. Canvas hanya menggambar ulang selama masih ada sel yang menyala.
variant: persegipixel, lingkarandot, ataubrushyang juga menyalakan sel di sekitarnya dengan lebih lembut. Gerakan cepat diisi, sehingga jejak tidak berlubang.- Saat elemen di dalamnya mendapat fokus keyboard, sel di sekitarnya menyala.
autoplaymenggambar jejak sendiri selama area terlihat dan kursor di tempat lain. - Warna dibaca dari token tema, sehingga mengikuti mode gelap. Dengan reduced motion tidak ada yang digambar. Atribut dan
classjatuh ke area.
Props
| Nama | Tipe | Default | Keterangan |
|---|---|---|---|
variant | "pixel" | "dot" | "brush" | "pixel" | pixel: sel persegi. dot: sel bulat seperti papan LED. brush: kuas lembut yang juga menyalakan sel di sekitar kursor. |
cellSize | number | 24 | Sisi satu sel dalam px. |
fade | number | 600 | Lama sel yang menyala memudar, dalam ms. |
color | "primary" | "success" | "warning" | "danger" | "ink" | "primary" | Token warna cahaya, dibaca dari tema sehingga mengikuti mode terang dan gelap. |
showGrid | boolean | false | Menggambar garis grid tipis di antara sel. |
autoplay | boolean | false | Menggambar jejak sendiri selama area terlihat, tab aktif, dan kursor di tempat lain. |
children / slot | ReactNode / slot | - | Konten di atas sel. Atur tata letaknya dengan class sendiri pada komponen. |
Aksesibilitas
- Canvas bersifat aria-hidden dan tidak menangkap pointer; konten di atasnya tetap terbaca dan bisa diklik.
- Saat elemen di dalamnya mendapat fokus keyboard, sel di sekitarnya menyala sebagai penanda fokus tambahan di samping cincin fokus biasa.
- Dengan reduced motion tidak ada yang digambar; canvas hanya menggambar ulang selama masih ada sel yang menyala.
Komponen terkait
Komponen markasui lain dengan class yang sama di setiap framework.
- Bottom NavigationBar bawah gaya aplikasi mobile. Pill meluncur ke item terpilih, labelnya muncul, dan bar bisa menciut jadi ikon saat konten discroll.
- Card StackTumpukan kartu bertingkat. Geser, tombol panah, atau tombol navigasi membuang kartu teratas lalu kartu berikutnya naik. Berputar, dengan indikator posisi.
- Chat MessagePesan dalam percakapan AI. Gelembung user di kanan, balasan asisten dengan avatar, aksi saat hover, indikator mengetik, dan efek streaming token opsional.
- Currency InputKolom uang yang memformat saat mengetik (Rp 12.500.000), menjaga posisi kursor, dan mengirim angka murni. Opsional chip nominal cepat.
- DockDock ala macOS. Ikon membesar halus mengikuti kursor atau fokus, label muncul di atas, item terbuka bertitik, dan memantul saat dibuka.
- Drag ElementsArea kartu atau stiker yang bisa diseret dengan momentum ringan di dalam batasnya. Panah menggeser item yang fokus, Escape mengembalikannya.