Skip to content

Instantly share code, notes, and snippets.

@dac09
Created July 22, 2021 12:55
Show Gist options
  • Save dac09/632568acc4c7e85b5423d847b2bc16b6 to your computer and use it in GitHub Desktop.
Save dac09/632568acc4c7e85b5423d847b2bc16b6 to your computer and use it in GitHub Desktop.
Using canvas to create static gif
import { css } from '@emotion/core'
import { Result } from 'antd'
import { useEffect, useRef } from 'react'
import { ListTapes } from 'types/graphql'
const previewCss = css`
border-radius: 12px;
max-height: 600px;
max-width: 100%;
`
interface TapePreviewProps {
tape: ListTapes['tapePage']['tapes'][0]
autoPlay?: boolean
focused?: boolean
}
const TapePreview = ({ tape, autoPlay = false }: TapePreviewProps) => {
const { contentType, tapeUrl } = tape
function playVideo(e) {
if (autoPlay === false) {
e.target.play()
}
}
function stopVideo(e) {
if (autoPlay === false) {
e.target.pause()
e.target.currentTime = 0
}
}
const staticGifRef = useRef<HTMLCanvasElement>()
const imgRef = useRef<HTMLImageElement>()
useEffect(() => {
const ctx = staticGifRef?.current?.getContext('2d')
const image = new Image()
image.src = imgRef?.current?.src
ctx?.drawImage(image, 0, 0)
}, [staticGifRef, imgRef])
if (contentType.includes('image')) {
return (
<div className="group">
<canvas
ref={staticGifRef}
className="fixed w-full opacity-100 group-hover:opacity-0"
></canvas>
<img
ref={imgRef}
src={tapeUrl}
css={previewCss}
alt=""
className="object-cover opacity-0 group-hover:opacity-100"
/>
</div>
)
} else if (contentType.includes('video')) {
return (
<video
css={previewCss}
muted
playsInline
autoPlay={autoPlay}
onMouseOver={(event) => playVideo(event)}
onMouseOut={(event) => stopVideo(event)}
onFocus={(event) => playVideo(event)}
onBlur={(event) => stopVideo(event)}
loop
className="object-cover"
>
<source src={tapeUrl} type="video/mp4"></source>
</video>
)
} else {
return (
<Result
status="404"
title="404"
subTitle="That tape doesn't look quite right"
/>
)
}
}
export default TapePreview
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment