Animate draggable element using velocity.js

独自空忆成欢 提交于 2019-12-24 04:26:23

问题


I am using velocity.js to animate a draggable SVG element as it is dragged by the user. However, velocity.js queues the previous mousemove co-ordinates & animates through all the subsequent mousemove co-ordinates. What I want is velocity.js not to queue the co-ordinates but animate to the latest co-ordinates as passed on by the function.

Check this jsFiddle

document.addEventListener("mousedown",mouseDown);
document.addEventListener("mouseup",endMove); 
var click=false;

var clickX, clickY;

var moveX=0, moveY=0; 

var lastMoveX=0, lastMoveY=0; 


function mouseDown(evt){

    evt.preventDefault(); 
    var element=(typeof (window.event) !=='undefined') ? evt.srcElement:evt.target;
    if(element.id==="mycirc")
    {
    click=true;
    clickX = evt.clientX;
    clickY = evt.clientY;
     }
document.addEventListener("mousemove",moveboth);          
return false;
}
function movexaxis(evt)
{
    var clx=evt.clientX-clickX;
     moveX = lastMoveX + clx;
     return moveX;
     }


function moveyaxis(evt)
{
      var cly=evt.clientY-clickY;
       moveY = lastMoveY + cly;
       return moveY;
     }

function moveboth(evt){ setTimeout(function move(){

    evt.preventDefault();

    var a=document.getElementById("mycirc"); 

    if(click){
        movexaxis(evt);
        moveyaxis(evt);
        Velocity(a,{translateX: moveX},{duration:"0ms"},  {queue:false});
        Velocity(a,{translateY: moveY },{duration:"0ms"},{queue:false});
        Velocity(a,"stop");
        }
    },34);
}
 function endMove(evt){
    click=false;
    lastMoveX = moveX;
    lastMoveY = moveY;     
}

回答1:


Dragging is not really a type of animation, so using Velocity is a major overkill. Since you already have the code that stores x and y coordinates, all that you need to do is use requestAnimationFrame() to update the element's transform to translate to these coordinates on each frame. And that's it (:



来源:https://stackoverflow.com/questions/27704974/animate-draggable-element-using-velocity-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!