LoginSignup
1
1

More than 1 year has passed since last update.

【ECサイト】refile と elevatezoom.js でお手軽画像拡大機能実装

Last updated at Posted at 2021-05-29

はじめに

プログラミングスクールでECサイトを共同開発中です。その際「商品画像拡大を簡単に実装できればなぁ」と思い実装してみたところちょっと苦戦したのでやり方をアウトプットします。

目標

できるだけ簡単にelevatezoomを虫眼鏡拡大オプションで実装します。

利用環境

rails 5.2.5
ImageMagick
refile
jquery.elevateZoom-3.0.8

※refileのインストールが終わっていて商品ページには商品画像が配置されている想定で進めます

elevatezoomとrefileについて

どんなzoomができるかについては https://www.elevateweb.co.uk/image-zoom/examples/ が1番分かり易いです。
とりあえず虫眼鏡拡大オプション動作させるには以下が必要になります。

<img id="〇〇" src="表示画像" data-zoom-image="表示画像より大きい画像"/>
$("#〇〇").elevateZoom({
  zoomType  : "lens",
  lensShape : "round",
  lensSize  : 200
});

elevatezoomとrefileの問題点
①elevatezoomはdata-zoom-imageというカスタムデータ属性と表示画像より大きい画像が必要
②refileのattachment_image_tagにカスタムデータ属性を入れるオプションは無さそう

問題点の解決策
①表示画像と表示画像より大きい画像は同じものを使用して表示画像をCSSで小さめに表示する
②jQueryであとからdata-zoom-imageをsrcの値を使って足す

ダウンロード

elevatezoom.js
①上記のgithubよりmasterをzipダウンロードしてください。
②ダウンロードしたzipファイルを解凍します。
③今回はjquery.elevateZoom-3.0.8.min.jsを使用します。

配置

①app/assets/javascriptsにjquery.elevateZoom-3.0.8.min.jsを配置

記述

①商品詳細ページのrefile画像へ記述

show.html.erb
<%= attachment_image_tag @model, :image, :fill, 800, 600, format: 'jpeg', id: "zoom" %>

※800x600としましたが、実際に表示されている画像はCSSで小さくしてください。(400x300とか)

②application.jsへ記述

application.js
$(document).on('turbolinks:load',function() {
  $(document).ready(function () {
   var dz_img = $("#zoom").attr('src'); //refileのsrcを取得します。
   $("#zoom").attr({'data-zoom-image': dz_img }); // data-zoom-imageにdz_imgを入れます。
   $("#zoom").elevateZoom({
          zoomType : "lens",
          lensShape : "round",
          lensSize : 200
      }); //elevateZoomを動かします。
  });
});

おわり

以上でおわりです。この方法で動きました。

1
1
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
1
1