如何优化我的代码,以便我可以正确加载它

时间:2016-11-25 06:52:15

标签: javascript html html5-canvas

我制作了这个代码,它确实有效,但是当我开始添加更多功能和东西时,它停止正确加载。有时会说数组的项目是未定义的,依此类推。并且,当我逐个测试它时,我注意到当我在2个模块之间发出警报时,它可能会起作用,可能是因为警报有助于代码的第一部分结束它所做的事情,因此下一个模块正确启动。我知道这段代码也可能不是很优化,但这从未发生在我身上,所以我想了解更多相关信息。

function Coordinates (x, y){
  this.x = x;
  this.y = y;
}

function Line (nombre, status, size) {
  this.coordinates = [];
  this.nombre = nombre;

  this.setCoordinates = function(x, y){
    this.coordinates.push(new Coordinates(x, y));
  }

  this.status = status;
  this.size = size;

  this.setStatus = function(number){
    this.status = number;
  }

  this.getColor = function(){
    switch (this.status) {
      case 0:
        return "yellow";
        break;
      case 1:
        return "orange";
        break;
      case 2:
          return "green";
        break;
      case 3:
          return "red";
        break;
    }
  }
};

var linesArray = [];
linesArray.pop();//I don't know why, but sometimes there is an undefined object inside

try{
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = process;
  xhr.open("GET", "http://localhost/raspizonasstatus.txt", true);
  xhr.send();

}catch(err){
  alert(err);

}finally{
  var xhr2 = new XMLHttpRequest();
  xhr2.onreadystatechange = process2;
  xhr2.open("GET", "http://localhost/raspizonascoordenadas.txt", true);
  xhr2.send();

}

function process(){
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    var aux = 1;

    for(item in Object.keys(resp)){
      var keyName = "zona"+aux;

      linesArray.push(
        new Line(
          Object.keys(resp)[item],
          parseInt(resp[keyName].status),
          parseInt(resp[keyName].size)
        )
      );
      aux++;
    }

  }
}

function process2(){
  if (xhr2.readyState == 4) {
    var resp2 = JSON.parse(xhr2.responseText);

    for(item in Object.keys(resp2)){
      for(part in Object.keys(resp2[Object.keys(resp2)[item]])){

        linesArray[item].setCoordinates(
          parseInt(resp2[Object.keys(resp2)[item]][part]["x"]),
          parseInt(resp2[Object.keys(resp2)[item]][part]["y"])
        );
      }
    }
  }
}

//////////////////////////This alert is needed to make this code run(show the lines in the canvas)/////////////////////////
alert("SOMETHING");

$(function(){
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var coordL = 0;

    for (var i = 0; i < linesArray.length; i++) {
      coordL = 0;
      drawLinesRect(
        defineLinesRect(
            linesArray[i].coordinates[coordL].x,
            linesArray[i].coordinates[coordL].y,
            linesArray[i].coordinates[coordL+1].x,
            linesArray[i].coordinates[coordL+1].y,
            linesArray[i].size),
        linesArray[i].getColor());

        if(linesArray[i].coordinates.length > 2){
          var count = linesArray[i].coordinates.length - 2;

          for (var j = 0; j < count; j++) {
            coordL++;
            drawLinesRect(
              defineLinesRect(
                  linesArray[i].coordinates[coordL].x,
                  linesArray[i].coordinates[coordL].y,
                  linesArray[i].coordinates[coordL+1].x,
                  linesArray[i].coordinates[coordL+1].y,
                  linesArray[i].size),
              linesArray[i].getColor());
          }

        }
    }

    function drawLine(x1,y1,x2,y2,lineWidth,color){
        ctx.fillStyle=color;
        ctx.strokeStyle=color;
        ctx.lineWidth=lineWidth;
        ctx.save();
        ctx.beginPath();
        ctx.moveTo(x1,y1);
        ctx.lineTo(x2,y2);
        ctx.stroke();
        ctx.restore();
    }

    function drawLinesRect(LinesRect,color){
        var r=LinesRect;
        ctx.save();
        ctx.beginPath();
        ctx.translate(r.translateX,r.translateY);
        ctx.rotate(r.rotation);
        ctx.rect(r.rectX,r.rectY,r.rectWidth,r.rectHeight);
        ctx.translate(-r.translateX,-r.translateY);
        ctx.rotate(-r.rotation);
        ctx.fillStyle=color;
        ctx.strokeStyle=color;
        ctx.fill();
        ctx.stroke();
        ctx.restore();
    }

    function defineLinesRect(x1,y1,x2,y2,lineWidth){
        var dx=x2-x1;
        var dy=y2-y1;
        var lineLength = Math.sqrt(dx*dx+dy*dy);
        var lineRadianAngle = Math.atan2(dy,dx);

        return({
            translateX:x1,
            translateY:y1,
            rotation:lineRadianAngle,
            rectX:0,
            rectY:-lineWidth/2,
            rectWidth:lineLength,
            rectHeight:lineWidth
        });
    }

    function processAction(Line){
      switch (Line.status) {
        case 0:
          break;
        case 1:
          var r = confirm("some text");
          if (r == true) {

          }
          break;
        case 2:
            var r = confirm("some text");
            if (r == true) {
            }
          break;
        case 3:
            var r = confirm("some text");
            if (r == true) {
            }
          break;
      }
    }

    function handleMouseDown(e){
      mouseX = parseInt(e.clientX-offsetX);
      mouseY = parseInt(e.clientY-offsetY);
      var coordL = 0;

      for (var i = 0; i < linesArray.length; i++) {
        coordL = 0;
        drawLinesRect(
          defineLinesRect(
              linesArray[i].coordinates[coordL].x,
              linesArray[i].coordinates[coordL].y,
              linesArray[i].coordinates[coordL+1].x,
              linesArray[i].coordinates[coordL+1].y,
              linesArray[i].size),
          "transparent");

          if(ctx.isPointInPath(mouseX,mouseY)){
            processAction(linesArray[i]);
            return;
          }

          if(linesArray[i].coordinates.length > 2){
            var count = linesArray[i].coordinates.length - 2;

            for (var j = 0; j < count; j++) {
              coordL++;
              drawLinesRect(
                defineLinesRect(
                    linesArray[i].coordinates[coordL].x,
                    linesArray[i].coordinates[coordL].y,
                    linesArray[i].coordinates[coordL+1].x,
                    linesArray[i].coordinates[coordL+1].y,
                    linesArray[i].size),
                  "transparent");
                  if(ctx.isPointInPath(mouseX,mouseY)){
                    processAction(linesArray[i]);
                    return;
                  }
            }
          }
      }
    }
    canvas.addEventListener("mousedown", handleMouseDown, false);

}); // end $(function(){});

0 个答案:

没有答案