Skip to content

Instantly share code, notes, and snippets.

@jesperlandberg
Created May 2, 2022 14:19
Show Gist options
  • Save jesperlandberg/004d15735b97ebd10c6ec0f3bbdbfebe to your computer and use it in GitHub Desktop.
Save jesperlandberg/004d15735b97ebd10c6ec0f3bbdbfebe to your computer and use it in GitHub Desktop.
export default function (el) {
const canvas = el
const ctx = canvas.getContext('2d')
const total = 76
const images = []
const size = { x: 0, y: 0, h: 0, w: 0 }
let count = 0
let prevCount = undefined
let width = 0
let height = 0
gsap.fromTo(el, {
yPercent: -25,
}, {
yPercent: 0,
ease: 'none',
scrollTrigger: {
trigger: dom.body,
endTrigger: el.parentNode,
start: 'top top',
end: 'bottom bottom',
scrub: true,
onUpdate: self => tick(self.progress)
}
})
function resize() {
const cbr = rect(el)
const dpr = 1
width = cbr.width * dpr
height = cbr.height * dpr
canvas.height = height
canvas.width = width
}
function tick(p) {
count = gsap.utils.clamp(0, total - 1, Math.ceil(total * p))
if (prevCount === count) return
draw(count)
prevCount = count
}
function currentSrc(i) {
if (store.dom.body.classList.contains('eng')) {
return `/wp-content/themes/sisource-theme/static/frames/hero/eng/frame_${i}.jpg`
} else {
return `/wp-content/themes/sisource-theme/static/frames/hero/frame_${i}.jpg`
}
}
function load() {
for (let i = 0; i < total; i++) {
const url = currentSrc(i)
const image = new Image()
image.onload = () => {
images[i] = image
i === 0 && (calcScale(), draw())
}
image.src = url
}
}
function calcScale() {
const image = images[0]
const scale = Math.max(width / image.width, height / image.height)
size.x = (width / 2) - (image.width / 2) * scale
size.y = (height / 2) - (image.height / 2) * scale
size.w = image.width * scale
size.h = image.height * scale
}
function draw() {
const { x, y, w, h } = size
const image = images[count]
if (!image) return
ctx.clearRect(0, 0, width, height)
image && ctx.drawImage(image, x, y, w, h)
}
function mount() {
resize()
load()
}
function unmount() {
}
mount()
return {
unmount
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment