使用新数据更新每个AJAX请求的HTML canvas标记

Lea*_*sed 8 html javascript jquery canvas html5-canvas

如果找到新用户或现有用户有新连接,我想在每个AJAX请求上更新我的画布.

我有他们之间的用户和连接:

 var data=[
           {
              "Id": 38,
               "Connections":[39,40],
               "Name":"ABc"
          },
           {
              "Id": 39,
               "Connections":[40],
               "Name":"pqr"
           },
           {
               "Id": 40,
               "Connections":[],
               "Name":"lmn"
           }]
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,用户Id:38已连接到user 39 and 40并且user 39 is connected to user 40 and user 40已连接到user 39 and user 38 so user 40 Connection array is blank.

我有一个Web服务,我将每1-2秒触发一次,以显示此页面上新加入的用户以及我存储在我的表中的现有用户之间的新连接,此Web服务将获取所有用户及其连接.

所以首先我的页面会加载,但之后我的页面将不会刷新,新的用户应该显示,新的连接应该与AJAX调用连接到我的Web服务.

但是随着ajax请求,一切都搞砸了.这是我创建JSBin.

输出我得到:

在此输入图像描述

我只有4个用户和3个连接,你可以在我的JSBin输出中看到它应该只有4个矩形,我不是添加更多的用户,但仍然得到这个混乱的输出.

源代码参考:参考小提琴

我试图获得输出,如上面的小提琴,但没有得到.

预期输出:4个带动画的矩形

更新了Js bin Demo:更新了JSBin

使用上面更新的JSBin我得到这个输出,但他们没有移动(动画不工作):

更新输出

小智 4

这些盒子没有移动,因为从未调用移动它们的代码。

如果将盒子动画部分移至updateUsers()主动画循环,它们就会动画化。

从此部分移动该部分:

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);
}
Run Code Online (Sandbox Code Playgroud)

到这里:

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);
}
Run Code Online (Sandbox Code Playgroud)

由于我们无法访问您正在使用的 Web 服务,并且假设数据已正确返回,因此我必须取消注释预定义数据才能制作一个有效的演示:

更新了jsbin