How does js move one element to another coordinate?

for example, if you want to move from 0 to 100 1px at this speed, you can move x coordinates + 1 per frame. What if you want to move obliquely from 0 ~ 0 to 100 ~ ~ 20 at this speed?

Mar.06,2021

x


css3 implementation:

div {

animation: myfirst 5s;

}

@ keyframes myfirst
{

0%   {left:0px; top:0px;}
100% {left:100px; top:20px;}

}

jquery implementation:

$("- sharpbox"). Animate ({left: "100px", top: "20px"});

then do it yourself:

function animate(sX,sY,eX,eY,time,call){
    this.currentX = sX,this.currentY = sY;
    this.speedX = (eX - sX)/(time*100),this.speedY = (eY - sY)/(time*100);
    
    this.start = function(){
        let vm =this;
        setTimeout(function(){
            if(vm.currentX < eX){
                vm.currentX += vm.speedX;
                vm.currentY += vm.speedY;
                call(vm.currentX,vm.currentY);
                vm.start();
            }
        },10)
        
    }
}
var callBack = function(x,y){
    console.log('x =>',x,'y =>',y)
}
var animate1 = new animate(0,0,200,100,5,callBack)
animate1.start()

:dom


was previously done with raf, which can calculate the distance of x-axis and y-axis movement per frame, and px under 5 * root sign (1 to 16) px, root sign (1 to 16). Then add this to the absolute position of the moving element.

Menu