最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Move image around browser window and bounce back on striking side wall - Stack Overflow

programmeradmin1浏览0评论

I am in phase of learning javascript. I'm working on a simple javascript (purely javascript without jquery etc) program for moving images across browser. As far as i understand, i can move image to left or right by addition or subtraction in img.style.left or img.style.right - But i need to know how can i bounce back image when it hits browser sidebar ?

So image goes first to left and when it hits browser side wall it rebounds back to right and on hitting right side wall, it again starts moving to left.

Kindly help me with this. Thanks in advance

I am in phase of learning javascript. I'm working on a simple javascript (purely javascript without jquery etc) program for moving images across browser. As far as i understand, i can move image to left or right by addition or subtraction in img.style.left or img.style.right - But i need to know how can i bounce back image when it hits browser sidebar ?

So image goes first to left and when it hits browser side wall it rebounds back to right and on hitting right side wall, it again starts moving to left.

Kindly help me with this. Thanks in advance

Share Improve this question asked Feb 27, 2014 at 18:05 ShumailShumail 3,1434 gold badges30 silver badges38 bronze badges 3
  • if you wanna use pure JS no Jquery the using cubic-bezier in css and add class dynamically when it hit the right or left... – Ash Commented Feb 27, 2014 at 18:11
  • @AshishMishra: See this JSfiddle: jsfiddle/shumail/ny9wK/1 i think window.load is not working here , you can try this on browser. my image goes straight beyond the side. – Shumail Commented Feb 27, 2014 at 18:23
  • yes you have to apply control on it by using if(parseInt(imgObj.style.left) <=parseInt( window.innerWidth)-50 ) after that in else you add class in which you define bounce effect!! – Ash Commented Feb 27, 2014 at 18:38
Add a ment  | 

4 Answers 4

Reset to default 2

Here is an answer in pure JavaScript, that is pretty straight-forward.

Basically, you'll want an interval (or a timeout that restarts itself over and over). Then, you grab the left value of the style (or the offsetLeft). You then add the direction * the distance per "tick" to the position, check for collision, and reverse direction as needed.

The code example below is pretty well mented.

A key to this is: don't set left or right. Pick one, and only control it. Trying to control both at once would drive you insane. Most of the time you'll want to control "left" since it is equivalent to "x" in a lot of languages (which is generally what you control for horizontal position).

JSFiddle: http://jsfiddle/dMJ2F/1/

var parent = document.getElementById('container'); // Element that holds the mover
var mover = document.getElementById('mover'); // The mover, can be anything
var dir = 1; // The direction we are moving... 1 is right, -1 is left.
var dist = 10; // The distance we move each "tick"

// The ID will let us stop it later if we want.
var intervalId = setInterval(function() {
    // Get the left, remove the "px" from the end and convert it to an integer.
    var posX = parseInt(mover.style.left.replace(/px$/, '')) || 0;

    // Add dir * dist
    posX += dir * dist;

    // If we are moving right and we've gone over the right edge...
    if (dir == 1 && posX + mover.offsetWidth > parent.offsetWidth) {
        // only move right to the edge...
        posX -= posX + mover.offsetWidth - parent.offsetWidth;
        // and change direction.
        dir *= -1
    // If we are moving left and we've gone over the left edge...
    } else if (dir == -1 && posX < 0) {
        // stop at zero...
        posX = 0;
        // and change direction...
        dir *= -1;
    }

    // Set the new position
    mover.style.left = posX + "px";
}, 100); // this number is how many milliseconds in between each move.
// Smaller interval time means smoother movement but slower performance.

You could use CSS3 animations:

#wrapper {
    position: relative;
    margin-right: 50px;
}
#ball {
    height: 50px;
    width: 50px;
    background: blue;
    border-radius: 50px;
    position: absolute;
    animation: animate 4s linear 0s infinite alternate;
}
@keyframes animate {
    from { left: 100%; }
    to { left: 0; }
}

Demo

You want to keep track of speed and direction, mainly, for this.

There's two ways to approach this:

  1. Using requestAnimationFrame to move the image as well as check to see whether it's hit the site of the browser,
  2. Using CSS3 animation (manipulation from JavaScript). Set a destination x (being the edge of the browser) once that animation is finished, do a reversed animation to the other side.

Check these resources out:

  • http://css-tricks./controlling-css-animations-transitions-javascript/
  • http://css-tricks./using-requestanimationframe/

While samanime's answer is correct, you should use requestAnimationFrame over setInterval if you just want to have it draw on the next repaint. There is performance improvements over the other methods listed in the docs.

I've modified samanime's code below to use requestAnimationFrame.

var parent = document.getElementById('container'); // Element that holds the mover
var mover = document.getElementById('mover'); // The mover, can be anything
var dir = 1; // The direction we are moving... 1 is right, -1 is left.
var dist = 10; // The distance we move each "tick"

// The ID will let us stop it later if we want.
function draw() {
    // Get the left, remove the "px" from the end and convert it to an integer.
    var posX = parseInt(mover.style.left.replace(/px$/, '')) || 0;
    
    // Add dir * dist
    posX += dir * dist;
    
    // If we are moving right and we've gone over the right edge...
    if (dir == 1 && posX + mover.offsetWidth > parent.offsetWidth) {
        // only move right to the edge...
        posX -= posX + mover.offsetWidth - parent.offsetWidth;
        // and change direction.
        dir *= -1
    // If we are moving left and we've gone over the left edge...
    } else if (dir == -1 && posX < 0) {
        // stop at zero...
        posX = 0;
        // and change direction...
        dir *= -1;
    }
    
    // Set the new position
    mover.style.left = posX + "px";
    window.requestAnimationFrame(draw); // Re-draw
}

window.requestAnimationFrame(draw);
#container {
    position: relative;
}

#mover {
    position: absolute;
    width: 100px;
    height: 100px;
    background: red;
}
<div id="container">
    <div id="mover"></div>
</div>

发布评论

评论列表(0)

  1. 暂无评论