LoginSignup
7
7

More than 5 years have passed since last update.

Reactで実装する虫眼鏡レンズ

Posted at

はじめに

いいライブラリがなかったので、Reactで虫眼鏡のような拡大鏡をパワーで実装してみましたというパワー系の記事です

ポイント

ポイントはhoverした時点で、imageタグのopacityを0にし、background-imageを拡大していくことで拡大鏡を実装しています。
マウスカーソルの位置を取得して、その値に応じてtransform-originbackground-positionを変えていきます。

デモンストレーション

magnifying_glass.mov.gif

ソースコード

JS
const imageUrl = 'http://img.kb-cdn.com/imgviewer/NVpIM2ptOHhYRzVmUk5rM1NrNlFxYVV6enV4aGk2UFRJMmxPckdDUUVNYmF1RnpSNUZYSGVySnNpclp0dGpMT2xQcndrSmo1U0dxdHR4WmNjZHZoM2RKUmpwbktBZ0E5eDFOd0I0RFdsNE1XbS9NbE1QWFMxa2JCaVVDRzdNMUtNWHcrWGkxdjdUQ2Jya25ZZ2t4Z2M5MEM3MGdZUGwvTEx3RHRScVhBdzM2QjFYNVNHQ2trNDhnWUFlelBZU2Jr?square=0'

class ZoomImage extends React.Component {
  state = {
    backgroundImage: `url(${imageUrl})`,
    backgroundPosition: '0% 0%',
    transformOrigin: '50% 50%',
    transform: 'scale(1)',
  };

  handleMouseMove = event => {
    const {
      left,
      top,
      width,
      height,
    } = event.currentTarget.getBoundingClientRect();
    const x = ((event.pageX - left) / width) * 100;
    const y = ((event.pageY - top) / height) * 100;

    this.setState({
      ...this.state,
      transformOrigin: `${x}% ${y}%`,
      backgroundPosition: `${x}% ${y}%`,
    });
  };

  handleMouseOver = () => {
    this.setState({ ...this.state, transform: 'scale(2.5)' });
  };

  handleMouseLeave = () => {
    this.setState({ ...this.state, transform: 'scale(1)' });
  };

  render = () => {
    return (
      <div className="zoomImgContainer">
        <div
          onMouseMove={this.handleMouseMove}
          onMouseOver={this.handleMouseOver}
          onMouseLeave={this.handleMouseLeave}
          style={this.state}
          className="zoomImgSection"
        >
          <img
            className="zoomImg"
            src={`${imageUrl}`}
            alt="画像がありません"
          />
        </div>
      </div>
    );
  };
}

React.render(<ZoomImage />, document.getElementById('app'));
CSS(Stylus)
.zoomImgContainer
  overflow hidden
  width 416px
  height 416px
  margin 0 auto

.zoomImgSection
  background-repeat no-repeat

.zoomImgContainer:hover
  .zoomImg
    opacity 0

.zoomImg
  display block
  width 100%
  pointer-events none
HTML
<div id="app"></app>

CodePen

See the Pen React at CodePen by kazukiii (@kazukiii) on CodePen.

以上です。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7