Rob
Rob

Reputation: 235

calculate movement based on time

So I am workng on a little project, mostly to help me learn better javascript and I'm having a little problem. I can do animations just fine, but my problem is.. I'm trying to figure out the math necessary to calculate the amount of change in pixels to move each step of the animation. So say my div is 450px wide and I'm saying animate({ width : 600, duration : 2000 }). that leaves 150px of total movement, but how much movement to I do for each frame if I'm calling my setTimeout function every 3 milliseconds. I know the solution is probably simple but for some reason, maybe just because I have been beating my head on a wall for while writing this whole thing and now I can't think enough to figure it out. I can show code examples if anyone needs. Thank you for the help in advance. As per request here is the code I have so far to do the animation...

animate : function(params, duration) {
    if(!params) {
        return this;
    } else {
        this.current = this._defCurrent;
        console.log(this.current);
        var time = (duration) ? duration : this.slow;
        var target;
        for(var index in params) {
            if(index == 'queue') {
                if(params[index]){
                    this.animQueue = true;
                } else {
                    this.animQueue = false;
                }
            } else {
                var current = parseFloat(this.getStyle(index));
                if(current < params[index]) {
                    target = params[index] - current;
                    animDirection = '+';
                } else {
                    target = current - params[index];
                    animDirection = '-';
                }
                totalMovement = target / time;
                animObj = {type : index, target : target, move : totalMovement, direction : animDirection, duration : time};
                this.setAnimQueue(animObj);
            }
        }
    }
    this.setTheTimeout();
},
setAnimQueue : function(obj) {
    var that = this;
    for(var i = 0, amt = (obj.duration * this.fps); i < amt; i++) {
        var fun = this.wrapFunction(that.doAnim, this, [obj.type, obj.move, obj.direction]);
        this.queue.push(fun);
    }
},
setTheTimeout : function() {
    var that = this;
    this.interValAmt = setInterval(function() {
        that.deQueue()
    }, this.fps);
},
doAnim : function(type, amount, direction) {
    var totalAmount = eval(parseFloat(this[type]()) + direction + amount);
    if(this.elem.style[this.toCamelCase(type)]) {
        this[type](totalAmount);
    } else {
        this[type](totalAmount)
    }
    return this;
}

Upvotes: 0

Views: 464

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798764

You have distance, and you have duration. Dividing them gives speed. Simply multiply the speed by the time increment to get the distance increment.

Upvotes: 1

Related Questions