react-parallax-hover
Version:
A pointer driven hover effect that rotates images in place with subtle parallax effects
322 lines (259 loc) • 16 kB
JavaScript
;
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = exports.ParallaxHover = void 0;
var _react = _interopRequireWildcard(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
var ParallaxWrapper = _styledComponents["default"].div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n transform-style: preserve-3d;\n transform: perspective(1000px);\n"])));
var ParallaxContainer = _styledComponents["default"].div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n position: relative;\n width: 100%;\n height: 100%;\n"])));
var ParallaxShadow = _styledComponents["default"].div(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n position: absolute;\n width: 95%;\n height: 95%;\n top: 2.55%;\n left: 2.55%;\n background: none;\n"])));
var ParallaxLayer = _styledComponents["default"].div(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n overflow: hidden;\n width: 100%;\n height: 100%;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n"])));
var ParallaxLighting = (0, _styledComponents["default"])(ParallaxLayer)(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n opacity: 0;\n"])));
var initialState = {
rotateX: 0,
rotateY: 0,
scale: 1,
shine: 0,
isHovered: false
};
var ParallaxHover = /*#__PURE__*/function (_Component) {
_inherits(ParallaxHover, _Component);
var _super = _createSuper(ParallaxHover);
function ParallaxHover(props) {
var _this;
_classCallCheck(this, ParallaxHover);
_this = _super.call(this, props);
_defineProperty(_assertThisInitialized(_this), "buildTransitionTimingString", function () {
var depth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var START_SPEED = 160;
var MAX_SPEED = 260;
var DEPTH_MODIFIER = 15;
var speedModifier;
if (depth > 0) {
speedModifier = START_SPEED + depth * DEPTH_MODIFIER;
} else if (depth > 10) {
speedModifier = MAX_SPEED;
}
return {
transition: "all ".concat(speedModifier, "ms ease-out")
};
});
_defineProperty(_assertThisInitialized(_this), "handleParallaxBegin", function () {
_this.setState({
isHovered: true,
shine: _this.props.shine
});
});
_defineProperty(_assertThisInitialized(_this), "handleParallaxEnd", function () {
_this.setState(initialState);
});
_defineProperty(_assertThisInitialized(_this), "handleParallaxMove", function (_ref) {
var pageX = _ref.pageX,
pageY = _ref.pageY;
var _this$props = _this.props,
width = _this$props.width,
height = _this$props.height,
rotation = _this$props.rotation,
scale = _this$props.scale;
var _window = window,
scrollTop = _window.scrollY,
scrollLeft = _window.scrollX;
var bounds = _this.wrapper.getBoundingClientRect();
var centerX = width / 2;
var centerY = height / 2;
var widthMultiplier = 360 / width;
var offsetX = (pageX - bounds.left - scrollLeft) / width;
var offsetY = (pageY - bounds.top - scrollTop) / height;
var deltaX = pageX - bounds.left - scrollLeft - centerX;
var deltaY = pageY - bounds.top - scrollTop - centerY;
var rotateX = (deltaY - offsetY) * (rotation / 100 * widthMultiplier);
var rotateY = (offsetX - deltaX) * (rotation / 100 * widthMultiplier);
var angleRad = Math.atan2(deltaY, deltaX);
var angleRaw = angleRad * 180 / Math.PI - 90;
var angle = angleRaw < 0 ? angleRaw + 360 : angleRaw;
_this.setState({
angle: angle,
rotateX: rotateX,
rotateY: rotateY,
scale: scale
});
});
_this.state = initialState;
return _this;
}
_createClass(ParallaxHover, [{
key: "buildTransformStrings",
value: function buildTransformStrings() {
var depth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var _this$state = this.state,
isHovered = _this$state.isHovered,
rotateX = _this$state.rotateX,
rotateY = _this$state.rotateY,
scale = _this$state.scale;
var scaleModifier = isHovered ? 1 + scale / 100 : 1;
var rotationXModifier = Math.floor(rotateX / depth);
var rotationYModifier = Math.floor(rotateY / depth);
var transformString = "scale(".concat(scaleModifier, ") rotateX(").concat(rotationXModifier, "deg) rotateY(").concat(rotationYModifier, "deg)");
return {
WebkitTransform: transformString,
MozTransform: transformString,
MsTransform: transformString,
OTransform: transformString,
transform: transformString
};
}
}, {
key: "calculateDistance",
value: function calculateDistance(bounds, offsetX, offsetY) {
var distanceX = Math.pow(offsetX - bounds.width / 2, 2);
var distanceY = Math.pow(offsetY - bounds.height / 2, 2);
return Math.floor(Math.sqrt(distanceX + distanceY));
}
}, {
key: "calculateShineFromCenter",
value: function calculateShineFromCenter(current) {
var _this$props2 = this.props,
width = _this$props2.width,
height = _this$props2.height,
shine = _this$props2.shine;
var max = Math.max(width, height);
return current / max * shine;
}
}, {
key: "renderLayers",
value: function renderLayers() {
var _this2 = this;
var _this$props3 = this.props,
borderRadius = _this$props3.borderRadius,
children = _this$props3.children,
height = _this$props3.height,
width = _this$props3.width;
var style = function style(depth) {
return _objectSpread({
height: "".concat(height, "px"),
width: "".concat(width, "px"),
borderRadius: "".concat(borderRadius, "px")
}, _this2.buildTransitionTimingString(depth));
};
if (!Array.isArray(children)) {
return /*#__PURE__*/_react["default"].createElement(ParallaxLayer, {
style: style(1),
className: "parallaxHover__layer"
}, children);
}
return children.map(function (layer, i) {
return /*#__PURE__*/_react["default"].createElement(ParallaxLayer, {
style: style(i + 2),
className: "parallaxHover__layer",
key: i
}, layer);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var _this$state2 = this.state,
angle = _this$state2.angle,
isHovered = _this$state2.isHovered,
shine = _this$state2.shine,
rotateX = _this$state2.rotateX;
var _this$props4 = this.props,
children = _this$props4.children,
borderRadius = _this$props4.borderRadius,
shadow = _this$props4.shadow,
width = _this$props4.width,
height = _this$props4.height;
var shadowPositionModifier = rotateX + shadow * shadow / 2;
var shadowBlurModifier = 20 + shadow * shadow;
var opacityModifier = isHovered ? 1 : 0;
var lightingShineModifier = shine * 0.1;
var wrapperStyles = {
width: width,
height: height
};
var innerContainerStyles = _objectSpread(_objectSpread({}, this.buildTransformStrings(1)), this.buildTransitionTimingString(1)); // prettier-ignore
var shadowStyles = _objectSpread(_objectSpread({}, this.buildTransitionTimingString(2)), {}, {
borderRadius: borderRadius + 'px',
opacity: opacityModifier,
boxShadow: "\n 0px ".concat(shadowPositionModifier, "px ").concat(shadowBlurModifier, "px rgba(0, 0, 0, 0.5),\n 0px ").concat(shadowPositionModifier * 0.33, "px ").concat(shadowBlurModifier * 0.33, "px 5px rgba(0, 0, 0, 0.5)")
});
var lightingStyles = _objectSpread(_objectSpread({}, this.buildTransitionTimingString(children.length)), {}, {
borderRadius: borderRadius + 'px',
opacity: opacityModifier,
backgroundImage: "linear-gradient(".concat(angle, "deg, rgba(255,255,255, ").concat(lightingShineModifier, ") 0%, rgba(255,255,255,0) 80%)")
});
return /*#__PURE__*/_react["default"].createElement(ParallaxWrapper, {
className: "parallaxHover__outter",
onMouseEnter: this.handleParallaxBegin,
onMouseLeave: this.handleParallaxEnd,
onMouseMove: this.handleParallaxMove,
onTouchStart: this.handleParallaxBegin,
onTouchMove: this.handleParallaxEnd,
onTouchEnd: this.handleParallaxMove,
style: wrapperStyles,
ref: function ref(wrapper) {
_this3.wrapper = wrapper;
}
}, /*#__PURE__*/_react["default"].createElement(ParallaxContainer, {
style: innerContainerStyles
}, /*#__PURE__*/_react["default"].createElement(ParallaxShadow, {
className: "parallaxHover__shadow",
style: shadowStyles
}), this.renderLayers(), /*#__PURE__*/_react["default"].createElement(ParallaxLighting, {
className: "parallaxHover__lighting",
style: lightingStyles
})));
}
}]);
return ParallaxHover;
}(_react.Component);
exports.ParallaxHover = ParallaxHover;
ParallaxHover.defaultProps = {
/** How fast the item scales up and down in MS */
speed: 100,
/** Rotation modifier */
rotation: 5,
/** Shadow darkness modifier */
shadow: 5,
/** Light shine brightness modifer */
shine: 5,
/** Default height */
height: 200,
/** Default width */
width: 200,
/** Default border radius */
borderRadius: 0
};
ParallaxHover.propTypes = {
children: _propTypes["default"].any,
width: _propTypes["default"].number.isRequired,
height: _propTypes["default"].number.isRequired,
shadow: _propTypes["default"].number,
rotation: _propTypes["default"].number,
shine: _propTypes["default"].number,
borderRadius: _propTypes["default"].number
};
var _default = ParallaxHover;
exports["default"] = _default;