Parallax image

Parallax image effect with zoom
2014-11-09 20:46

A couple of days ago I ran across a campaign site for a upcoming game title and found a cool image parallax scrolling effect that followed the mouse movement. It also used a small zoom effect once you got closer to the center of the image. This effect look really neat so I figured I give it a go myself. I started out with a single image of a forest environment which I worked out into three layers in Photoshop. A background, a middle part and a foreground.

 

layers

Then I got to work on the code, I used html, css and typescript (javascript). Once I got the layers positioned with css inside a wrapper div I started working on the math in javascript to make the magic happen.

wrapper.on('mousemove', function (e) {
    var percX = e.offsetX/wrapper.width();
    var percY = e.offsetY/wrapper.height();   percYPos = -0.5 + (1.0 - percY);
    percXPos = -0.5 + (1.0 - percX);

    if (percX > 0.5) {
        percX = 1.0 - percX;
    }
    scale = 1.1 + (0.4 * percX);
    move();
});

So as you can see in the code above there are some percentage calculations to calculate where in the image the cursor is in both x and y axis. Basically we want to calculate a percentage that increases when we move the cursor towards the center of the image. But if we pass the center we flip the calculation and start decreasing it again. Now we have everything except the positioning and scaling of the images done. This is just a css thing done with jQuery.

var backgroundX = 50*percXPos;
var backgroundY = 10*percYPos; 

background.css({
    transform : ”scale(”+(scale)+”) translate3d(”+(backgroundX)+”px,”+(backgroundY)+”px,0)”
}); 

var middleX = 80*percXPos;
var middleY = 30*percYPos;
middle.css({
    transform : ”scale(”+scale+”) translate3d(”+middleX+”px,”+(middleY)+”px,0)”
}); 

var foregroundX = 150*percXPos;
var foregroundY = 60*percYPos; 

foreground.css({
    transform : ”scale(”+ (scale + 0.1) +”) translate3d(”+foregroundX+”px,”+(foregroundY)+”px,0)”
});

So there you have a quick version of it. Feel free to check out the original code on the link and please leave a comment if you like it.

 

Demo


Recent blog posts


The Travel (Working title)

So as I wrote in the previous blog post, I’m working on a game. The working title for the game is now set to “The Travel” and why that is I’ll keep as a secret for now....

Read more


Defold - A game engine

Most of you probably never heard of a game engine called Defold. It’s a 2d game engine developed by King, which is made so that you...

Read more