JS/Canvas单行动画

3
我想使用JavaScript和Canvas标签制作一条单线的动画。除了以下问题,我能够轻松完成这个任务:
如果您要绘制一条直线,则它可以正常工作 - 我有一个间隔(10毫秒),每次增加1像素,因此如果它从150px(X)/ 20px(Y)到150px(X)/ 200px(Y) - 一切看起来都很好。
问题在于向右或向左的线 - 例如从150px(X)/ 20px(Y)到35px(X)/ 200px(Y)
我的动画失败了,因为每10ms向X和Y两个方向各添加1px会使线先撞到左侧(35px),然后再从那里走到终点Y。
这是我的代码(您需要Firefox或Opera) - 如您所见,线条较早地撞到了左侧,这就是我的问题。 :(
<html>
<script type="text/javascript" src="http://www.prototypejs.org/assets/2008/9/29/prototype-1.6.0.3.js"></script>
<style>
body {background: #fff; color: #ccc;}
</style>

<script type="text/javascript">
var startpointx = 150;
var startpointy = 25;
var curposx = 150;
var curposy = 25;
var myinterval;

function init() {
        myinterval = setInterval( ' animate(35, 250) ', 10);
}

function random (n)
{
  return (Math.floor (Math.random() * n));
}

function animate(endpointx, endpointy) {
        if (curposx == endpointx && curposy == endpointy){
            clearInterval(myinterval);
            drawShape(endpointx, endpointy);
            return false;
        } else {

            if(curposx != endpointx){
                if(endpointx > curposx) {
                    curposx = curposx + 1;
                } else {
                    curposx = curposx - 1;
                }
            }
            if(curposy <= endpointy){
            curposy = curposy + 1;
            }
        }
    drawShape(curposx, curposy, "#000");
}

function drawShape(tendpointx, tendpointy, clor){
     var canvas = document.getElementById('cnvs');
     var ctx = canvas.getContext('2d');

       ctx.clearRect(0,0,310,400);
       ctx.strokeStyle = clor;
         ctx.beginPath();
         ctx.moveTo(startpointx ,startpointy );
         ctx.lineTo(tendpointx,tendpointy);
         ctx.stroke();
}  

//  
init();

</script>


<body>
<canvas id="cnvs" width="310" height="400" style="border: 1px solid #ccc;"></canvas>
</body>
</html>
1个回答

3

假设你想要从点(0, 0)画一条直线到点(100, 200)。水平距离是100,垂直距离是200,这意味着当你将终点向右移动1个像素时,你需要将其向下移动2个像素(或者,对于一个垂直像素,需要向右移动0.5个像素)。

您可以使用以下算法来计算差异:

   var deltaX = Math.abs( endpointx - startpointx );
   var deltaY = Math.abs( endpointy - startpointy );
   var diffX = 1, diffY = 1;
   if( deltaX > deltaY ){
      diffY = deltaY / deltaX;
   }
   else if( deltaX < deltaY ) {
      diffX = deltaX / deltaY;
   }

在您的动画中,需要按照diffX和diffY分别递增/递减curposx和curposy,而不是递增/递减1。此计算应在animate()函数外部完成(因为它总是返回相同的结果)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接