Make moving Rect more smooth

前端 未结 1 1593
孤街浪徒
孤街浪徒 2021-01-18 13:22

I want to make \"animation\" of my Rect more smooth. Currently it\'s really clunky. I know the reason for it. One of the coordinates becomes wanted value before the other.

相关标签:
1条回答
  • 2021-01-18 14:08

    That's because you set dir [+-1, +-1] instead [dx, dy] (the actual displacement), which are not always proportional.

    Have a look at the modified snippet:

    var canvas = document.getElementById('canvas');
    var ctx = document.getElementById('canvas').getContext('2d');
    
    var x;
    var y;
    
    var tx = tx || 0;
    var ty = ty || 0;
    
    var xDir;
    var yDir;
    
    function followMouse(e) {
      x = e.pageX;
      y = e.pageY;
      moveObject();
    }
    
    function moveObject() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      var scale =  0.2 * Math.max(canvas.width, canvas.height);
      xDir = (x - tx) / scale;
      yDir = (y - ty) / scale;
      tx = tx != x ? tx + xDir : tx;
      ty = ty != y ? ty + yDir : ty;
    
    
      ctx.fillRect(tx - 25, ty + 25, 50, 10);
      if (tx != x || ty != y) {
        window.requestAnimationFrame(moveObject);
      }
    }
    
    function resizeCanvas() {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };
    
    canvas.addEventListener('mousemove', _.throttle(function(e) {
      followMouse(e);
    }, 100));
    
    window.addEventListener('resize', resizeCanvas, false);
    
    resizeCanvas();
    html,
    body {
      margin: 0;
      height: 100%;
    }
    canvas {
      display: block;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    <canvas id="canvas" style="border: 1px solid black"></canvas>

    0 讨论(0)
提交回复
热议问题