jeudi 7 février 2019

How to simply create an image reflection effect in JavaScript/CSS?

I have spent some time to look up how to best create a dynamic image reflection effect.

Options I found were:

  • non-standard browser tags such as -webkit-reflect,

  • adding libraries from <2012 that all have outdated dependencies and fail when combining with e.g. up to date JQuery 3, or

  • dropping the idea of dynamic image reflections and relying on GIMP/Photoshop.

  • Also most existing solutions fail on non plain background, i.e. textures.

The drawbacks of the above lie at hand. Unfortunately I do not have a web blog where to post what I came up with, yet I think it would be worth sharing:

  1. Add an image to your HTML:
<img class="reflect" src="some/image.png" />

  1. Add the following CSS rules:
img {
  position: absolute;
}

img.reflection {
  position: absolute;
  opacity: 0.4;
  margin-top: 4px;
  -webkit-mask-image: -webkit-linear-gradient(transparent 75%, black 100%);
  mask-image: linear-gradient(transparent 75%, black 100%);
  -webkit-transform: translateY(100%) scaleY(-1) ;
  transform: translateY(100%) scaleY(-1);
}

  1. Extend JQuery with the following function:
$.fn.reflect = function() {
    var reflection = this.clone();
    this.after(reflection);
    reflection.addClass("reflection");
};

  1. Reflect all the images:
$("img.reflect").reflect();

That's it, have a nice day,

Daniel





Aucun commentaire:

Enregistrer un commentaire