Skip to content

Instantly share code, notes, and snippets.

@cbdyzj
Created April 10, 2022 01:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbdyzj/daeb016c89100440ed27d1f90eca2203 to your computer and use it in GitHub Desktop.
Save cbdyzj/daeb016c89100440ed27d1f90eca2203 to your computer and use it in GitHub Desktop.
XNano.jsx
import React, { Component, useRef } from 'react'
import styled from '@emotion/styled'
import { sleep } from '../../utils/schedule.js'
const Container = styled.div`
box-sizing: border-box;
position: relative;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
`
const Title = styled.div`
position: relative;
bottom: 5rem;
font-size: 4.5rem;
line-height: 1;
color: #fff;
text-shadow: 1px 1px 3px rgb(36 37 47 / 25%);
`
const IMAGE_URL = 'https://source.unsplash.com/random/1600x900'
class ImageBackground extends Component {
constructor(props, context) {
super(props, context)
this.state = {
backgroundPosition: 'center',
backgroundSize: 'cover',
position: 'absolute',
inset: '0',
opacity: '0',
zIndex: '-1',
}
}
componentDidMount() {
const image = new Image()
image.src = IMAGE_URL
image.addEventListener('load', () => {
this.setState(state => {
return {
...state,
backgroundImage: `url(${IMAGE_URL})`,
transition: 'opacity 1s ease',
opacity: '1',
}
})
})
}
nextBackgroundImage() {
this.setState(state => {
return {
...state,
opacity: '0',
}
}, () => {
const imageUrl = `${IMAGE_URL}?bust=${new Date().getTime()}`
Promise.all([
new Promise((resolve) => {
const image = new Image()
image.src = imageUrl
image.addEventListener('load', resolve)
}),
sleep(1000),
]).then(() => {
this.setState(state => {
return {
...state,
backgroundImage: `url(${imageUrl})`,
opacity: '1',
}
})
})
})
}
render() {
return (<div style={this.state}/>)
}
}
export default function XNano() {
const imageBackgroundRef = useRef()
function onClick() {
imageBackgroundRef.current?.nextBackgroundImage()
}
return (
<Container onClick={onClick}>
<Title>nano</Title>
<ImageBackground ref={imageBackgroundRef}/>
</Container>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment