Skip to content

Capturing different image sizes with one drop area

Martin Metsalu edited this page Dec 21, 2017 · 3 revisions

Capturing different image sizes with one drop area

This method expects you have at least 2 image data types under your data model (e.g photo, photo_thumbnail).

Followed by in your element.tpl layout:

<figure>
  {% if editmode %}
    {% assign image = element.photo %}
    {% assign imageObj = '{"url": "' | append: image | append: '"}' | escape %}
    <div class="drop-picture" data-image-object="{{ imageObj }}"></div>
  {% else %}
    <img src="{{ element.photo }}" alt="{{ element.title }}">
  {% endif %}
</figure>

{% editorjsblock %}
  
  <script src='{{ site.static_asset_host }}/libs/edicy-tools/latest/edicy-tools.js'></script>
  <script type="text/javascript">
    var pictureDropArea = new Edicy.ImgDropArea(document.querySelector(".drop-picture"), {

      change: function(data) {

        var photo = null, 
            photo_thumbnail = null;

        if (data !== null) {

          var sizes = data.imageSizes.reverse();
          var large_sizes = sizes.filter(function(image) { return image.width >= 1600 });
          var block_sizes = sizes.filter(function(image) { return image.width >= 400 });
          var image_large = large_sizes.length ? large_sizes[0] : data;
          var image_block = block_sizes.length ? block_sizes[0] : data;
          var photo = image_large.url;
          var photo_thumbnail = image_block.url;

        } 

        var xhr = new XMLHttpRequest();
        xhr.open('PUT', '/admin/api/elements/{{ element.id }}', true);
        xhr.setRequestHeader('Content-Type', 'application/json');

        var data = (JSON.stringify({
          element: {
            values: {
              photo: photo, 
              photo_thumbnail: photo_thumbnail
              }
            }
          })
        );

        xhr.send(data);

      }
    });
  </script>
{% endeditorjsblock %}

And in your elements.tpl layout:

 <div class="photo"><img src="{{ element.photo_thumbnail }}" alt="Photo" class="photo-img"></div>

Clone this wiki locally