Update HTML canvas tag on every AJAX request with new data

后端 未结 2 1194
野趣味
野趣味 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:35

    I worked from your Source Code Reference Fiddle, which worked pretty ok to me.

    Added a couple of things:

    First of a seperate function to add a user to the users array. This way, users can easily be added after a successful webservice call.

    Second, affffded a couple of helper functions to get random positions and directions.

    function addUser(user) {
        users.push({
        id: user.UserId,
        connections: user.Connections,
        width: 80,
        height: 80,
        x: getRandomX(),
        y: getRandomY(),
        dir: {
            x: getDir(),
            y: getDir()
        }
      });
    }
    
    // the success callback from your webservice
    // guess this receives a `user` object with Id and Connections
    // for the test we use `getRandomConnections` 
    function getDataFromWebService() {
      let newUser = { "UserId": Date.now(), "Connections": getRandomConnections() };
      addUser(newUser);
    }
    

    Fiddle

    When you connect your webservice, you can ditch the getRandomConnections function and reference. In your webservice success callback, make sure you have an object in the format:

    { UserId: 1337, Connections: [1, 2] }
    

    Pass that object to the addUser function.

提交回复
热议问题