Skip to content

Commit

Permalink
add: png file thumbnails
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoecheza committed Nov 8, 2023
1 parent 9e4d6b3 commit afff4af
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@
align-items: center;
justify-content: center;
}

.AssetPreview canvas {
width: 100%;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,72 @@ import { toWearableWithBlobs } from './utils'
import { Props } from './types'

import './AssetPreview.css'
import { useRef } from 'react'

export function AssetPreview({ value, onScreenshot }: Props) {
const onLoad = React.useCallback(() => {
const wp = WearablePreview.createController(value.name)
void wp.scene.getScreenshot(1024, 1024).then(($) => onScreenshot($))
}, [])
const WIDTH = 300
const HEIGHT = 300

export function AssetPreview({ value, onScreenshot }: Props) {
return (
<div className="AssetPreview">
{isGltf(value.name) ? (
<WearablePreview
id={value.name}
blob={toWearableWithBlobs(value)}
disableAutoRotate
disableBackground
projection={PreviewProjection.ORTHOGRAPHIC}
camera={PreviewCamera.STATIC}
onLoad={onLoad}
/>
<GltfPreview value={value} onScreenshot={onScreenshot} />
) : value.name.endsWith('png') ? (
<PngPreview value={value} onScreenshot={onScreenshot} />
) : (
<IoIosImage />
)}
</div>
)
}

function GltfPreview({ value, onScreenshot }: Props) {
const onLoad = React.useCallback(() => {
const wp = WearablePreview.createController(value.name)
void wp.scene.getScreenshot(WIDTH, HEIGHT).then(($) => onScreenshot($))
}, [])

return (
<WearablePreview
id={value.name}
blob={toWearableWithBlobs(value)}
disableAutoRotate
disableBackground
projection={PreviewProjection.ORTHOGRAPHIC}
camera={PreviewCamera.STATIC}
onLoad={onLoad}
/>
)
}

function PngPreview({ value, onScreenshot }: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null)

const url = URL.createObjectURL(value)
const img = new Image(WIDTH, HEIGHT)
img.src = url

img.onload = () => {
const canvas = canvasRef.current
const ctx = canvasRef.current?.getContext('2d')
const canvas2 = document.createElement('canvas')
const ctx2 = canvas2.getContext('2d')

if (canvas && ctx && ctx2) {
canvas.height = canvas.width * (img.height / img.width)

canvas2.width = img.width * 0.5
canvas2.height = img.height * 0.5
ctx2.drawImage(img, 0, 0, canvas2.width, canvas2.height)
ctx2.drawImage(canvas2, 0, 0, canvas2.width * 0.5, canvas2.height * 0.5)
ctx.drawImage(canvas2, 0, 0, canvas2.width * 0.5, canvas2.height * 0.5, 0, 0, canvas.width, canvas.height)
ctx.drawImage(img, 0, 0, WIDTH, HEIGHT)

onScreenshot(canvas.toDataURL('image/png'))

canvas2.remove()
}
}

return <canvas ref={canvasRef} id="asset-png-preview" touch-action="none"></canvas>
}

0 comments on commit afff4af

Please sign in to comment.