Skip to content

Instantly share code, notes, and snippets.

@soyuka
Created February 3, 2020 18:19
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 soyuka/2454c6314aa03f117c8938a4151d0ac5 to your computer and use it in GitHub Desktop.
Save soyuka/2454c6314aa03f117c8938a4151d0ac5 to your computer and use it in GitHub Desktop.
import React from 'react'
import './close-pixelate.js'
export default class PixelatedImg extends React.Component {
constructor(props) {
super(props)
this.imgRef = React.createRef();
this.parentNode = React.createRef();
this.pixelated = null
}
pixelate() {
if (!this.imgRef.current || !this.imgRef.current.parentNode) {
return
}
const options = {shape: 'square', size: this.props.resolution, offset: 0, alpha: 1, ...this.props}
this.parentNode.current = this.imgRef.current.parentNode
this.pixelated = new window.ClosePixelation(this.imgRef.current, [options])
}
removeCanvas() {
this.parentNode.current.removeChild(this.pixelated.canvas)
}
createImg() {
const imgRef = document.createElement('img')
imgRef.className = this.props.className
imgRef.src = this.props.src
imgRef.alt = this.props.alt
imgRef.onLoad = this.handleImageLoaded.bind(this)
imgRef.onError = this.handleImageErrored.bind(this)
this.imgRef.current = imgRef
this.parentNode.current.appendChild(imgRef)
}
handleImageLoaded() {
requestAnimationFrame(() => {
this.pixelate()
})
}
handleImageErrored() {
console.error('image load error')
}
componentDidUpdate(prevProps) {
if (this.props.src !== prevProps.src) {
this.removeCanvas()
this.createImg()
}
}
componentWillUnmount() {
if (!this.pixelated && this.parentNode.current) {
return
}
this.removeCanvas()
}
render() {
return <img className={this.props.className} ref={this.imgRef} src={this.props.src} alt={this.props.alt} onLoad={this.handleImageLoaded.bind(this)} onError={this.handleImageErrored.bind(this)} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment