Created
February 3, 2020 18:19
-
-
Save soyuka/2454c6314aa03f117c8938a4151d0ac5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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