Update HTML canvas tag on every AJAX request with new data

后端 未结 2 1195
野趣味
野趣味 2020-12-06 06:57

I want to update my canvas on every AJAX request if new user is found or there is new connection of existing users.

I have users and connections between them:

<
2条回答
  •  忘掉有多难
    2020-12-06 07:58

    The boxes aren't moving because the code for moving them is never called.

    If you move the part animating the boxes from updateUsers() to your main animation loop they will animate.

    Move the section from this part:

    function updateUsers() {
      fetchData();
    
      // this part ------------------------------------------------------
      $.each(users, function(index, user) {
        if (user.x <= 0) user.dir.x = 1;
        if (user.x + user.width > canvas.width) user.dir.x = -1;
        if (user.y <= 0) user.dir.y = 1;
        if (user.y + user.height > canvas.height) user.dir.y = -1;
    
        user.x += user.dir.x;
        user.y += user.dir.y;
      });
      // to here --------------------------------------------------------
    
      //window.setTimeout(updateUsers, 1000 / 60);
      window.setTimeout(updateUsers, 9000);
    }
    

    to here:

    function drawUsers() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      $.each(users, function(index, user) {
        ctx.beginPath();
        ctx.rect(user.x, user.y, user.width, user.height);
        ctx.strokeStyle = 'red';
        ctx.stroke();
    
        if (user.connections != null) {
          user.connections.forEach(function(id) {
            const other = users.find(user => user.id === id);
    
            ctx.beginPath();
            ctx.moveTo(user.x + (user.width / 2), user.y + (user.height / 2));
            ctx.lineTo(other.x + (other.width / 2), other.y + (other.height / 2));
            ctx.strokeStyle = 'black';
            ctx.stroke();
          });
        }
      });
    
      // animate here
      $.each(users, function(index, user) {
        if (user.x <= 0) user.dir.x = 1;
        if (user.x + user.width > canvas.width) user.dir.x = -1;
        if (user.y <= 0) user.dir.y = 1;
        if (user.y + user.height > canvas.height) user.dir.y = -1;
    
        user.x += user.dir.x;
        user.y += user.dir.y;
      });
      window.requestAnimationFrame(drawUsers);
    }
    

    Since we don't have access to the web service you're using, and assuming the data is correctly returned, I had to uncomment the predefined data to make a working demo:

    Updated jsbin

提交回复
热议问题