如果发现新用户或存在现有用户的新连接,我想在每次 AJAX 请求时更新我的 Canvas 。
我有用户和他们之间的联系:
var data=[
{
"Id": 38,
"Connections":[39,40],
"Name":"ABc"
},
{
"Id": 39,
"Connections":[40],
"Name":"pqr"
},
{
"Id": 40,
"Connections":[],
"Name":"lmn"
}]
在上面的示例中,Id:38
的用户连接到用户 39 和 40
,用户 39 连接到用户 40 和用户 40
> 已连接到 用户 39 和用户 38,因此用户 40 连接数组为空
。
我有一个 Web 服务,我将每 1-2 秒触发一次,以在此页面上显示新加入的用户以及我存储在表中的现有用户之间的新连接,该 Web 服务将获取所有用户及其连接.
所以一开始我的页面会加载,但之后我的页面不会刷新,应该显示新用户,新连接应该通过 AJAX 调用连接到我的网络服务。
但是对于 ajax 请求,一切都变得一团糟。这是 JSBin I have created .
我得到的输出:
正如您在我的 JSBin 输出中看到的那样,我只有 4 个用户和 3 个连接,那么它应该只有 4 个矩形,我没有添加更多用户,但仍然得到这个困惑的输出。
源代码引用:Reference Fiddle
我正在尝试获取上面 fiddle 中所示的输出,但没有得到。
预期输出:4 个带有动画的矩形
更新Js bin Demo:Updated JSBin
使用上面更新的 JSBin,我得到了这个输出,但它们没有移动(动画不工作):
最佳答案
盒子没有移动,因为移动它们的代码从未被调用。
如果您将动画框的部分从 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);
}
到这里:
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);
}
由于我们无法访问您正在使用的网络服务,并且假设数据已正确返回,我不得不取消对预定义数据的注释以制作一个工作演示:
关于javascript - 使用新数据在每个 AJAX 请求上更新 HTML canvas 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37208156/