Skip to content

Instantly share code, notes, and snippets.

@ebrelsford
Created January 5, 2017 21:00
Show Gist options
  • Save ebrelsford/d525b2607891b3d0b1a7ab75822a164e to your computer and use it in GitHub Desktop.
Save ebrelsford/d525b2607891b3d0b1a7ab75822a164e to your computer and use it in GitHub Desktop.
React component that pins overlaid children on top of an element's background image
class PinnedOverlay extends React.Component {
constructor(props) {
super(props);
var image = new Image();
image.src = window.getComputedStyle(this.props.overlaid)['background-image'].replace(/"/g,"").replace(/url\(|\)$/ig, "");
this.imageWidth = image.width;
this.imageHeight = image.height;
this.aspectRatio = this.imageWidth / this.imageHeight;
this.state = {
computedLeft: props.left,
computedTop: props.top
};
this.updatePinnedLocation = debounce(this.updatePinnedLocation, 100);
}
updatePinnedLocation() {
const windowWidth = document.body.clientWidth;
const imageScaledHeight = windowWidth / this.aspectRatio;
this.setState({
computedLeft: this.props.left * (windowWidth / this.imageWidth),
computedTop: this.props.top * (imageScaledHeight / this.imageHeight)
});
}
componentDidMount() {
this.updatePinnedLocation();
window.addEventListener("resize", this.updatePinnedLocation.bind(this));
}
componentWillUnmount() {
window.removeEventListener("resize", this.updatePinnedLocation.bind(this));
}
render() {
return (
<div className="pinned-overlay" style={{
position: 'absolute',
left: `${this.state.computedLeft}px`,
top: `${this.state.computedTop}px`
}}>
{this.props.children}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment