An example of using css3+ jquery to achieve a parallax effect

Source: Internet
Author: User
Tags in degrees
Use CSS and jquery to make it look as if it were the original effect.








Eventually



In this tutorial, I'll use css,html and jquery to create an approximate Apple TV parallax effect, and if you're reading, I'm assuming you have a basic understanding of the three technologies mentioned above.



Nonsense not much to say, to begin the first part.



HTML page



Our page structure looks like this:




<p class="poster">  <p class="shine"></p>
  <p class="layer-1"></p>
  <p class="layer-2"></p>
  <p class="layer-3"></p>
  <p class="layer-4"></p>
  <p class="layer-5"></p>
</p>


First, you need a style class for.postertheplayer thatpcontains 5 other styles in thisp.pThere is a p on these five layersshineto add some flash effects.



CSS Section



First, add the following code to ensure thatbodythe height of the page section is the entire page height:



Body, HTML {height:100%; min-height:100%;}


Then give somebodybackground gradient color:



Body {background:linear-gradient (to bottom, #f6f7fc 0, #d5e1e8 40%);}


In order for.posterthe effect to be rotated, the parent container needs to set the perspective and transform effect. As we can see,pthe parent container isbodyitself, so add the following CSS code:



Body {    background:linear-gradient (to bottom, #f6f7fc 0, #d5e1e8 40%);    transform-style:preserve-3d;    Transform:perspective (800px);}


Now set the style and size of the card, let it center on the page, add some fillet and shadow effect:



. poster {    width:320px;    height:500px;    Position:absolute;    top:50%; left:50%;    Margin: -250px 0 0-160px;    border-radius:5px;    box-shadow:0 45px 100px rgba (0, 0, 0, 0.4);    Overflow:hidden;}


In order to center the poster, you need to setpositionthe value to,absolutetop:50%' left:50% ', the uppermarginvalue isphalf the height of the negative number, the left side of themarginvalue isphalf the width of negative numbers. Remember that the center is also the center of the.posterentire page.






Shadow effect



We can use the following CSS selectors to select all the layers:



P[class *= ' layer-']


.posterIt's already been designed, so look at the effect.



So, CSS chooses all the class names that contain "layer-"p.



Now, set the value of all the layers to be, the value is, the size of thepositionabsolutebackground-repeatno-repeatbackground-positiontop leftlayer background is 100% width and the auto height.




p[class*="layer-"] {    position: absolute;    top: -10px; left: -10px;    right: -10px; bottom: -10px;    background-size: 100% auto;    background-repeat: no-repeat;    background-position: 0 0;    transition:0.1s;
}


Notice thattop,leftrightbottomThe value is -10px, the purpose is to make the layer size ratioposterof 20px, so that at the time of the inspection at each layer will not see the edge of the layer.



The following is a background for each layer:




.layer-1 {    background-image: url('http://designmodo.com/demo/apple-tv-parallax/images/1.png');
}.layer-2 {    background-image: url('http://designmodo.com/demo/apple-tv-parallax/images/2.png');
}.layer-3 {    top: 0; bottom: 0;    left: 0; right: 0;    background-image: url('http://designmodo.com/demo/apple-tv-parallax/images/3.png');
}.layer-4 {    background-image: url('http://designmodo.com/demo/apple-tv-parallax/images/4.png');
}.layer-5 {    background-image: url('http://designmodo.com/demo/apple-tv-parallax/images/5.png');
}


In thelayer-3section, the layer does not move, so the dimensions do not have to be too large.






Complete the static effect



JavaScript section



Before you start, make sure you've introduced the jquery library, or you'll get an error.



The logic of parallax effect is this, whenever the mouse moves, depending on the position of the cursor,.posterthetransforms:translateYrotaterotateYproperties will change. The farther the cursor is from the upper-left corner of the page, the more dramatic the animation.



The formula is similar to this: the position/width of the offsetx=0.5-cursor from the top of the page.



For each element's value to be different, the value returned by each cursor formula is multiplied by a custom value, and the HTML code is returned to each animated layer element to adddata-offset=数字the attribute.




<p data-offset="15" class="poster">
    <p class="shine"></p>
    <p data-offset="-2" class="layer-1"></p>
    <p class="layer-2"></p>
    <p data-offset="1" class="layer-3"></p>
    <p data-offset="3" class="layer-4"></p>
    <p data-offset="10" class="layer-5"></p>
</p>


.layersthe rules for each are the same, but we apply them totranslateYandtranslateXattributes.



data-offsetThe larger the value of the property, the more pronounced the animation will be, which can be changed under the experience of these values.



For code readability, we assign values to variables in JavaScript, variables.poster$poster, and variables that.shine$shine$layerrepresent all layers,whrepresenting the width and height of the page.



var $poster = $ ('. Poster '), $shine = $ ('. Shine '), $layer = $ (' p[class*= "layer-"] ");


Now you need to consider the problem of getting to the cursor position when the cursor is moving. We can use$(window)mousemoveevents to implement, this event will return a JavaScript object containing the location information we need and other variables that we do not use temporarily.



$(window).on('mousemove', function(e) {    var w=e.currentTarget.innerWidth,h=e.currentTarget.innerHeight;    var offsetX = 0.5 - e.pageX / w, /* where e.pageX is our cursor X coordinate */
    offsetY = 0.5 - e.pageY / h,
    offsetPoster = $poster.data('offset'), /* custom value for animation depth */
    transformPoster = 'translateY(' + -offsetX * offsetPoster + 'px) rotateX(' + (-offsetY * offsetPoster) + 'deg) rotateY(' + (offsetX * (offsetPoster * 2)) + 'deg)';    /* apply transform to $poster */
    $poster.css('transform', transformPoster);    /* parallax foreach layer */    /* loop thought each layer */    /* get custom parallax value */    /* apply transform */
    $layer.each(function() {        var $this = $(this);        var offsetLayer = $this.data('offset') || 0; /* get custom parallax value, if element docent have data-offset, then its 0 */        var transformLayer = 'translateX(' + offsetX * offsetLayer + 'px) translateY(' + offsetY * offsetLayer + 'px)';

        $this.css('transform', transformLayer);
    });
});


The next step is to use the formula explained above to calculate theoffsetYoffsetXvalue and then apply the parallax effect to.poserteach poster layer.



Very cool, now we have a small part with a parallax effect.






Basic completion



But not yet, the glossy part of the poster hasn't been set yet.



Now go back to the CSS section, give.shinep absolute positioning, add a gradient color effect, set thez-indexproperty value to 100, and let it on top of all the layers.



. Shine {    position:absolute;    top:0; left:0; right:0; bottom:0;    Background:linear-gradient (90deg, Rgba (255,255,255,.5) 0%,rgba (255,255,255,0) 60%);    z-index:100;}


There has been a beautiful glitter layer on the poster, but in order to achieve a more realistic effect, the light should change as the cursor moves.






More realistic.



How do we do it? Maybe you remember the boring third day math class, and when you think about the formula you're never going to use, we use it now.



Therefore, the angle of inclination should be equal to the opposite value of the angle of the triangle formed by the cursor and the center of the poster. (Remember, the center of the poster is the center of the entire page, which is one-second of the width and height of the page)






Angle



First, find the right-angled edge of the triangle formed by the cursor and the center of the page, and make a right triangle after the cursor is connected to the center.



Then useMath.atan2()the function to get the angle value of the center point. Note that the return value of this function is represented by the Radian value, so we have to change the degree of the angle in the CSS to use the following formula:



Radian Value *180/pi = angle value



var $poster = $('.poster');    var $shine = $('.shine');    var $layer = $('p[class *= "layer-"]');

    $poster.data("offset",15);

    $(window).on('mousemove', function(e) {        var w=e.currentTarget.innerWidth,h=e.currentTarget.innerHeight;        var offsetX = 0.5 - e.pageX / w, /* where e.pageX is our cursor X coordinate */
        offsetY = 0.5 - e.pageY / h,
        offsetPoster = $poster.data('offset'), /* custom value for animation depth */
        transformPoster = 'translateY(' + -offsetX * offsetPoster + 'px) rotateX(' + (-offsetY * offsetPoster) + 'deg) rotateY(' + (offsetX * (offsetPoster * 2)) + 'deg)';

        dy = e.pageY - h / 2,
        dx = e.pageX - w / 2,
        theta = Math.atan2(dy,dx), /* get angle in radians */
        angle = theta * 180 / Math.PI; /* convert rad in degrees */        /* apply transform to $poster */
        $poster.css('transform', transformPoster);        /* parallax foreach layer */        /* loop thought each layer */        /* get custom parallax value */        /* apply transform */
        $layer.each(function() {            var $this = $(this);            var offsetLayer = $this.data('offset') || 0; /* get custom parallax value, if element docent have data-offset, then its 0 */            var transformLayer = 'translateX(' + offsetX * offsetLayer + 'px) translateY(' + offsetY * offsetLayer + 'px)';

            $this.css('transform', transformLayer);
        });
    });


You will find that the range of angle values is from-180-180 degrees, and the following code fixes this problem so that the angle value is from 0- degrees:



 


Now that the angle is there, you can dynamically change the angle value of the gradient color as the cursor moves:



90) + 'deg, rgba(255,255,255,' + e.pageY / h + ') 0%,rgba(255,255,255,0) 80%)'); 


You are welcome to join the Learning Exchange Group if you encounter any problems or want to acquire learning resources in the learning process.
343599877, we learn the front-end together!



Note: The reason for subtracting 90 degrees is that thelinear-gradientattribute is needed, and if you use it-webkit-linear-gradient, the attribute is-moz-linear-gradientnot necessary.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.