在AJAX回调和呈现PIXIJS之间处理程序流时遇到了问题

Having trouble with program flow - juggling between AJAX callbacks and rendering PIXI JS

本文关键字:程序 遇到 问题 处理 之间 回调 AJAX PIXIJS      更新时间:2023-09-26

我在使js脚本流畅地运行时遇到了问题。这是一个接收和发送鼠标坐标并绘制坐标的脚本。

这是:

//Initialize PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);
//requestAnimFrame(animate);
function animate() {
    console.log("Draw.");
    requestAnimFrame(animate);
    renderer.render(stage);
}
//Function for receiving data.
indx = 0;
var makeRequest = function(){
   var ajaxFunction = function(){
      if(ajaxRequest.readyState == 4){
        var pointsStr = ajaxRequest.responseText.split("C"); //The co-ordinates are received in this form: "pointCpointCpointCpoint...pointCindex"
        indx = parseInt(pointsStr[pointsStr.length - 1]);
        for (i = 0; i < pointsStr.length - 1; i++) {
            if(pointsStr[i] != ""){
                var points = pointsStr[i].split(",");
                mouseX = parseInt(points[0]);
                mouseY = parseInt(points[1]);
                var graphics = new PIXI.Graphics(); //Why create new graphics every time? PixiJS bugs out if I don't. Probably also something to do with the flow.
                graphics.lineStyle(1, 0xFFFFFF);
                stage.addChild(graphics);
                graphics.drawRect(mouseX,mouseY,1,1);
                renderer.render(stage);
                console.log("Received.")
            }
        }
      } 
   }
   var ajaxRequest = new XMLHttpRequest();
   ajaxRequest.onreadystatechange = ajaxFunction;
   ajaxRequest.open("GET", "http://127.0.0.1/receiveData/0=" + indx, true);
   ajaxRequest.send();
}
//Function for sending data.
var sendRequest = function(arr){
   var t = ""
   for (var i = 0; i < arr.length; i++) {
        t += arr[i].x.toString() + "," + arr[i].y.toString() + "C";
   }
   t = t.slice(0,-1);
   var ajaxRequest = new XMLHttpRequest();
   ajaxRequest.open("POST", "http://127.0.0.1/sendData/" + t, true);
   ajaxRequest.send();
   console.log("Send.")
}
pos = {
    x: 0,
    y: 0
}
var mouseRecording = new Array();
document.addEventListener('mousemove', function(e){ 
    var p = pos;
    p.x = e.clientX || e.pageX; 
    p.y = e.clientY || e.pageY;
    mouseRecording.push(pos);
    console.log("" + p.x + "," + p.y)
}, false);
var interval = setInterval(function(){
    console.log("Make Request.");
    sendRequest(mouseRecording);
    makeRequest();
}, 100);

从根本上讲,问题在于流程确实不一致。

例如,它只需要POST和GET 10秒钟,没有运行回调,但随后突然会运行200个请求,然后可能偶尔会出现屏幕渲染等

让程序充分流动的正确方法是什么?

关于函数命名和职责的一些注意事项:1。如果你的函数有一个非常通用的短名称,并且上面有一个注释,说明了一些不同的东西,那么去掉这个注释并重命名你的函数。2.你的功能应该只做它说它做它做的事情,而不是别的。3.您的函数不应修改其父作用域。副作用使调试变得困难。

也就是说,让我们先把它分解成一大堆小函数,它们做得很少,不可能做错什么。并命名,这样他们就不会做任何其他事情。

//Initialize PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);
function httpRequest(method, url, success, fail) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 ) {
      if(xmlhttp.status == 200){
        success(xmlhttp.responseText);
      }
      else {
        fail();
      }
    }
  }
  xmlhttp.open(method, url, true);
  xmlhttp.send();
}
function getRequest(url, success, fail) {
  httpRequest('GET', url, success, fail);
}
function postRequest(url, success, fail) {
  httpRequest('POST', url, success, fail);
}
function buildDataStringFromCoords(coords) {
  return coords.map(function(coord) {
    return coord.x.toString() + ',' + coord.y.toString();
  }).join('C');
}
function buildCoordsFromDataString(dataString) {
  return dataString.split('C').map(function(coordString) {
    var points = coordString.split(',');
    return {x:+points[0], y:+points[1]};
  });
}
function renderCoords(coords) {
  var graphics = new PIXI.Graphics(); //Why create new graphics every time? PixiJS bugs out if I don't. Probably also something to do with the flow.
  graphics.lineStyle(1, 0xFFFFFF);
  stage.addChild(graphics);
  graphics.drawRect(coords.x, coords.y, 1, 1);
  renderer.render(stage);
}
function requestCoords(indx, success, fail) {
  var url = 'http://127.0.0.1/receiveData/0=' + indx;
  getRequest(
    url, 
    function(response) {
      var coords = buildCoordsFromDataString(response);
      success(coords);
    },
    function() {
      fail();
    }
  );
}
var sendCoords = function(coords, success, fail) {
  var url = 'http://127.0.0.1/sendData/' + buildDataStringFromCoords(coords);
  postRequest(
    url,
    function() {
      success();
    },
    function() {
      fail();
    }
  );
}
pos = {
  x: 0,
  y: 0
};
var mouseRecording = new Array();
document.addEventListener('mousemove', function(e){ 
  var p = pos;
  p.x = e.clientX || e.pageX; 
  p.y = e.clientY || e.pageY;
  mouseRecording.push(pos);
  console.log('Mouse moved', p.x, p.y);
}, false);
var interval = setInterval(function(){
  console.log("Make Request.");
  sendCoords(
    mouseRecording,
    function() {
      console.log('Successfully sent coords', mouseRecording);
    },
    function() {
      console.log('Failed to send coords', mouseRecording);
    }
  );
  requestCoords(
    indx,
    function(coords) {
      console.log('Successfully fetched coords', coords);
      coords.forEach(function(coord) {
        renderCoords(coord);
      });
      console.log('Rendered coords', indx);
    },
    function() {
      console.log('Failed to get coords', indx);
    }
  );
}, 100);

现在,我们可以编写一些测试来证明每个部分都是"正确的",这样你就不必每次出现问题时都要经历整个大事件。例如:

function testBuildDataStringFromCoords() {
  return buildDataStringFromCoords([{x:123,y:456},{x:987,y:654}]) === '123,456C987,654';
}

这可能不会完全解决你的问题,但我希望它能让你的生活更轻松,让问题更透明。