JavaScript and CSS · Pencil trail effect
#pencil-trail {
display: none;
position: fixed;
opacity: .65 ;
z-index: -1 ;
mix-blend-mode: difference;
inset: 0 ;
width: 100 %;
height: 100 %;
pointer-events: none;
}
body { isolation: isolate; }
:where ( .contact, .research-section, .education-section, .career-ambition-band, .cad-section, .service-band-light, .service-band-cad) {
position: relative;
}
:where ( .contact, .research-section, .education-section, .career-ambition-band, .cad-section, .service-band-light, .service-band-cad) ::before {
content: '' ;
position: absolute;
inset: 0 ;
z-index: -2 ;
background: var ( --band-background) ;
pointer-events: none;
}
@media ( any-pointer: fine) and ( prefers-reduced-motion: no-preference) {
#pencil-trail { display: block; }
}
import { trailStrength } from './pencil-trail-strength.js' ;
import { createTrailStorage } from './pencil-trail-storage.js' ;
const canvas = document.querySelector ( '#pencil-trail' ) ;
const context = canvas?.getContext ( '2d' ) ;
const motion = window.matchMedia ( '(any-pointer: fine) and (prefers-reduced-motion: no-preference)' ) ;
if ( context) {
const step = 6 ;
const color = '#8dc4db' ;
const scale = Math.min ( window.devicePixelRatio || 1 , 2 ) ;
const tilePixels = 512 ;
const tileSize = tilePixels / scale;
const history = new Map ( ) ;
const tail = [ ] ;
const storage = createTrailStorage ( restoreBatch) ;
let previous = null ;
let distance = 0 ;
let frame = 0 ;
function stroke ( target, segment, strength) {
target.strokeStyle = color;
target.lineCap = 'round' ;
target.globalAlpha = .15 + .31 * strength ** 1.15 ;
target.lineWidth = 1.25 + 2.5 * strength;
target.beginPath ( ) ;
target.moveTo ( segment.from.x, segment.from.y) ;
target.lineTo ( segment.to.x, segment.to.y) ;
target.stroke ( ) ;
}
function record ( segment, strength) {
const pad = 3 ;
const left = Math.floor ( ( Math.min ( segment.from.x, segment.to.x) - pad) / tileSize) ;
const right = Math.floor ( ( Math.max ( segment.from.x, segment.to.x) + pad) / tileSize) ;
const top = Math.floor ( ( Math.min ( segment.from.y, segment.to.y) - pad) / tileSize) ;
const bottom = Math.floor ( ( Math.max ( segment.from.y, segment.to.y) + pad) / tileSize) ;
for ( let row = top; row <= bottom; row++) {
for ( let column = left; column <= right; column++) {
const key = row + ":" + column;
let tile = history.get ( key) ;
if ( !tile) {
const surface = document.createElement ( 'canvas' ) ;
surface.width = surface.height = tilePixels;
tile = surface.getContext ( '2d' ) ;
if ( !tile) continue ;
tile.setTransform ( scale, 0 , 0 , scale, -column * tilePixels, -row * tilePixels) ;
history.set ( key, tile) ;
}
stroke ( tile, segment, strength) ;
}
}
}
function settle ( segment) {
record ( segment, 0 ) ;
}
function saveTrail ( ) {
endStroke ( ) ;
void storage.flush ( true ) ;
}
function restoreBatch ( values) {
for ( let index = 0 ; index < values.length; index += 4 ) {
const x = values[ index] ;
const y = values[ index + 1 ] ;
const nextX = values[ index + 2 ] ;
const nextY = values[ index + 3 ] ;
if ( Math.abs ( nextX - x) > step + 1 || Math.abs ( nextY - y) > step + 1 ) continue ;
record ( { from: { x, y } , to: { x: nextX, y: nextY } } , 0 ) ;
}
scheduleRedraw ( ) ;
}
function redraw ( ) {
frame = 0 ;
context.resetTransform ( ) ;
context.globalAlpha = 1 ;
context.clearRect ( 0 , 0 , canvas.width, canvas.height) ;
const x = Math.round ( window.scrollX * scale) ;
const y = Math.round ( window.scrollY * scale) ;
const left = Math.floor ( x / tilePixels) ;
const right = Math.ceil ( ( x + canvas.width) / tilePixels) ;
const top = Math.floor ( y / tilePixels) ;
const bottom = Math.ceil ( ( y + canvas.height) / tilePixels) ;
for ( let row = top; row < bottom; row++) {
for ( let column = left; column < right; column++) {
const tile = history.get ( row + ":" + column) ;
if ( tile) context.drawImage ( tile.canvas, column * tilePixels - x, row * tilePixels - y) ;
}
}
context.setTransform ( scale, 0 , 0 , scale, -x, -y) ;
for ( const segment of tail) {
stroke ( context, segment, trailStrength ( distance - segment.distance) ) ;
}
}
function scheduleRedraw ( ) {
if ( !frame) frame = requestAnimationFrame ( redraw) ;
}
function endStroke ( ) {
previous = null ;
if ( !tail.length) return ;
for ( const segment of tail) settle ( segment) ;
tail.length = 0 ;
distance = 0 ;
scheduleRedraw ( ) ;
}
function resize ( ) {
if ( !motion.matches) return ;
endStroke ( ) ;
canvas.width = Math.round ( canvas.clientWidth * scale) ;
canvas.height = Math.round ( canvas.clientHeight * scale) ;
scheduleRedraw ( ) ;
}
window.addEventListener ( 'pointermove' , event => {
if ( !motion.matches || event.pointerType !== 'mouse' ) return ;
const point = { x: event.pageX, y: event.pageY } ;
if ( !previous) {
previous = point;
return ;
}
const dx = point.x - previous.x;
const dy = point.y - previous.y;
const length = Math.hypot ( dx, dy) ;
if ( length < 2 ) return ;
let from = previous;
const count = Math.ceil ( length / step) ;
for ( let i = 1 ; i <= count; i++) {
const to = { x: previous.x + dx * i / count, y: previous.y + dy * i / count } ;
distance += length / count;
tail.push ( { from, to, distance } ) ;
storage.append ( from, to) ;
from = to;
}
previous = point;
while ( tail.length && trailStrength ( distance - tail[ 0 ] .distance) === 0 ) {
settle ( tail.shift ( ) ) ;
}
scheduleRedraw ( ) ;
} , { passive: true } ) ;
window.addEventListener ( 'blur' , endStroke) ;
window.addEventListener ( 'scroll' , ( ) => {
if ( !motion.matches) return ;
endStroke ( ) ;
scheduleRedraw ( ) ;
} , { passive: true } ) ;
document.addEventListener ( 'pointerout' , event => {
if ( !event.relatedTarget) endStroke ( ) ;
} ) ;
document.addEventListener ( 'visibilitychange' , ( ) => {
if ( document.hidden) saveTrail ( ) ;
} ) ;
window.addEventListener ( 'pagehide' , saveTrail) ;
window.addEventListener ( 'pageshow' , event => {
if ( event.persisted && motion.matches) void storage.restore ( ) ;
} ) ;
window.addEventListener ( 'resize' , resize) ;
motion.addEventListener ( 'change' , ( ) => {
if ( motion.matches) {
void storage.restore ( ) ;
resize ( ) ;
}
else endStroke ( ) ;
} ) ;
if ( motion.matches) void storage.restore ( ) ;
resize ( ) ;
}
export function trailStrength ( distanceBehind) {
const solidLength = 45 ;
const fadeLength = 280 ;
const fade = ( distanceBehind - solidLength) / fadeLength;
return 1 - Math.min ( 1 , Math.max ( 0 , fade) ) ;
}
const storeName = 'strokes' ;
const legacyKey = 'portfolio-pencil-trail' ;
const legacyIdKey = 'portfolio-pencil-legacy-id' ;
const backupPrefix = 'portfolio-pencil-pending:' ;
const sessionKey = 'portfolio-pencil-session' ;
export function createTrailStorage ( restoreBatch) {
const rendered = new Set ( ) ;
const pending = new Map ( ) ;
let database;
let session;
let coordinates = [ ] ;
let timer;
let saving = false ;
function open ( ) {
return database ??= new Promise ( ( resolve, reject) => {
const request = indexedDB.open ( 'portfolio-pencil' , 1 ) ;
request.onupgradeneeded = ( ) => request.result.createObjectStore ( storeName) ;
request.onsuccess = ( ) => resolve ( request.result) ;
request.onerror = ( ) => reject ( request.error) ;
} ) ;
}
function makeId ( ) {
return crypto.getRandomValues ( new Uint32Array ( 4 ) ) .join ( '-' ) ;
}
function show ( id, values) {
if ( rendered.has ( id) ) return ;
restoreBatch ( values) ;
rendered.add ( id) ;
}
function restoreBackup ( ) {
for ( const key of Object.keys ( sessionStorage) ) {
if ( !key.startsWith ( backupPrefix) ) continue ;
restorePending ( key.slice ( backupPrefix.length) , sessionStorage.getItem ( key) ) ;
}
const old = sessionStorage.getItem ( legacyKey) ;
if ( old !== null ) {
const id = sessionStorage.getItem ( legacyIdKey) || makeId ( ) ;
sessionStorage.setItem ( legacyIdKey, id) ;
restorePending ( id, old) ;
}
}
function restorePending ( id, raw) {
try {
const values = JSON.parse ( raw) ;
if ( !Array.isArray ( values) || values.length % 4 || !values.every ( Number.isSafeInteger) ) return ;
if ( rendered.has ( id) ) return ;
const batch = Int32Array.from ( values) ;
show ( id, batch) ;
pending.set ( id, batch) ;
} catch {
}
}
async function restore ( ) {
try {
session = sessionStorage.getItem ( sessionKey) ;
if ( !session) {
const id = makeId ( ) ;
sessionStorage.setItem ( sessionKey, id) ;
session = id;
}
restoreBackup ( ) ;
void save ( ) ;
const db = await open ( ) ;
const range = IDBKeyRange.bound ( [ session, '' ] , [ session, '\uffff' ] ) ;
const request = db.transaction ( storeName) .objectStore ( storeName) .openCursor ( range) ;
request.onsuccess = ( ) => {
const cursor = request.result;
if ( !cursor) return ;
show ( cursor.key[ 1 ] , cursor.value) ;
cursor.continue ( ) ;
} ;
} catch {
}
}
function append ( from, to) {
if ( !session) return ;
coordinates.push ( Math.round ( from.x) , Math.round ( from.y) , Math.round ( to.x) , Math.round ( to.y) ) ;
timer ??= setTimeout ( ( ) => flush ( ) , 750 ) ;
}
function flush ( backup = false ) {
clearTimeout ( timer) ;
timer = undefined ;
if ( coordinates.length) {
const id = makeId ( ) ;
rendered.add ( id) ;
pending.set ( id, Int32Array.from ( coordinates) ) ;
coordinates = [ ] ;
}
if ( backup) {
try {
for ( const [ id, batch] of pending) {
sessionStorage.setItem ( backupPrefix + id, JSON.stringify ( Array.from ( batch) ) ) ;
}
} catch {
}
}
return save ( ) ;
}
async function save ( ) {
if ( saving || !pending.size) return ;
saving = true ;
try {
const db = await open ( ) ;
while ( pending.size) {
const batches = [ ...pending] ;
await new Promise ( ( resolve, reject) => {
const tx = db.transaction ( storeName, 'readwrite' ) ;
tx.oncomplete = resolve;
tx.onabort = ( ) => reject ( tx.error) ;
const store = tx.objectStore ( storeName) ;
for ( const [ id, batch] of batches) store.put ( batch, [ session, id] ) ;
} ) ;
for ( const [ id] of batches) {
pending.delete ( id) ;
try {
sessionStorage.removeItem ( backupPrefix + id) ;
if ( sessionStorage.getItem ( legacyIdKey) === id) {
sessionStorage.removeItem ( legacyKey) ;
sessionStorage.removeItem ( legacyIdKey) ;
}
} catch {
}
}
}
} catch {
} finally {
saving = false ;
}
}
return { append, flush, restore } ;
}
Scroll to read the full code ↓