Monday, December 21, 2015

Casting a Reflection Image Using Pure Javascript

This is mainly for fun or educational purposes only. This is inspired by a carousel javascript plugin with reflection at the bottom of each image which looks like they are standing on a solid marble. Since it is an awesome idea, I tried to do some coding if it is able to be done by just pure Javascript. Yes, they are done and the codes are presented as follows:


<a href="javascript:renderReflection()">Render Reflection</a>


var height,width;
var tmpDiv,tmpDiv2,i,j,k,l,m,n;
var img = new Image();
var file = 'img/phone_icon2.png';
img.src = file;
img.onload = function() {
 height = this.height;
 width = this.width;

tmpDiv = document.createElement("span");
tmpDiv.innerHTML = '<img id=img0 src="'+file+'">'; = 'absolute'; = '300px'; = '150px'; = "imgSpan";

function renderReflection() {

 k=0, l=-0.25, m=50, n=1; // n=speed of fade, // m=percentage of fade, // l=reflection direction

 for (i=1; i<=height; i++) {
 tmpDiv = document.createElement("span"); = "line"+i; = '1px'; = width+'px'; = 'absolute'; = 'hidden';

 j = i*n+(height*((100-m)/100));
 if (j>height) { j=height; } = ((height-j+1)/height*10)/10; = ((height-j+1)/height*10)/10;

 tmpDiv2 = document.createElement("span");
 tmpDiv2.innerHTML = '<img id=img'+i+' src="'+file+'">'; = 'absolute'; = -1*(height-i-1)+'px'; = 'alpha(opacity=' + Math.round((height-j+1)/height*100) + ')';

 k+=l; = document.getElementById('imgSpan').offsetLeft + k + 'px'; = height + document.getElementById('imgSpan').offsetTop + i + 'px';




You can adjust the style of the reflection by changing the value for l, m or n.

l is the control of the direction for the reflection. A negative value will move the reflection to the left and a postive value will move it to the right. A zero value will cast the reflection straight down.

m is the percentage of the reflection to be rendered. A value of 50 will only allow a maximum 50% of the reflection to be shown. The reflection image will look like being cut into half.

n is the fading speed of the reflection image. A value of 2 will double up the fading speed which result in only half of the reflection image being rendered. A value of 3 will triple up the fading speed which result in only a third of the reflection image being rendered.

The following is the screen capture of the trial runs.

The result of k=0, l=-0.25, m=50, n=1:

The result of k=0, l=0, m=100, n=1.25:

The result of k=0, l=1, m=85, n=2:

You can change the file name and path to something else by modifying var file = 'img/phone_icon2.png';! Enjoy!

P.S.: You need to click on the Render Reflection link to run the reflection rendering function in case you are not aware of.

No comments:

Post a Comment