Почему мои фигуры соединяются, когда я рисую их на холсте JavaScript? - PullRequest
0 голосов
/ 06 ноября 2019

Когда я рисую несколько кругов на холсте, они как бы собираются вместе, образуя странную форму. У меня есть 25 «х» и «у» значения, чтобы нарисовать круги, хранящиеся в массиве. Я не уверен, что это потому, что значения «x» и «y» двух или более кругов одинаковы. Можно ли как-то предотвратить это и / или убедиться, что значения x и y в кружках не меньше 10 от любых других значений? Спасибо.

Редактировать: Я нашел решение для этого благодаря Ник Парсонс. Я все еще задаюсь вопросом, могу ли я проверить, являются ли два или более значений «x» или «y» величиной x (x обозначает число) близко друг к другу, например, так: если два разных значения «x» имеют разницу меньше, чем10, журнал «слишком близко» в консоли.

Изображение проблемы:

Мой JavaScript: (Я пытался добавить полезные комментарии)

    var canvas = document.getElementById("canvas");

    var ctx = canvas.getContext("2d");

    var bubbleData = generateBubbles(); //Array the x and y values are stored in

    var bubbleDataLength = bubbleData.length;

    var bubbledataX = bubbleData[0].x;

    var bubbleDataY = bubbleData[0].y;

    var currentX;

    var currentY;

    function generateBubbles() {
        var generatedBubbleData = [];

        var bubbleCount = 0;
        var maxBubbleCount = 25;

        var bubbleX = 0;
        var bubbleY = 0;

        function yCalc() { //Function that returns the y value of each circle
            var currentY;
            var mathRandom = Math.floor(Math.random() * 101);
            if(mathRandom < 21) {
                bubbleY = 600;
            }

            if(mathRandom < 41 && mathRandom > 20) {
                bubbleY = 500;
            }

            if(mathRandom < 61 && mathRandom > 40) {
                bubbleY = 400;
            }

            if(mathRandom < 81 && mathRandom > 60) {
                bubbleY = 300;
            }

            if(mathRandom < 101 && mathRandom > 80) {
                bubbleY = 200;
            }

            return currentY;
        }

        var mathRandom = Math.floor(Math.random() * 101);

        function xCalc() { //Function that returns the x value of each circle
            var currentX;
            if(mathRandom < 26) {
                bubbleX = Math.random() * 150;
            }

            if(mathRandom < 51 && mathRandom > 25) {
                bubbleX = Math.random() * 175;
            }

            if(mathRandom < 76 && mathRandom > 50) {
                bubbleX = Math.random() * 200;
            }

            if(mathRandom > 75) {
                bubbleX = Math.random() * 250;
            }
            return currentX;
            }

            while(bubbleCount < 25) { //Only allows 25 x and y values
            currentX = xCalc();
            currentY = yCalc();


            generatedBubbleData.push({
                x: bubbleX,
                y: bubbleY
            });

            if(bubbleCount <= 25) { 
                bubbleCount++; 
                mathRandom = Math.floor(Math.random() * 101);
                xCalc(); 
            }
        }
            return generatedBubbleData;
    }

    generateBubbles();

    function draw() {
        canvas.width = window.innerWidth; // Sets canvas width and doesn't make drawings blurry
        canvas.height = window.innerHeight; // Sets canvas height and doesn't make drawings blurry
        ctx.fillStyle = "red";
        ctx.beginPath(); 
        bubbleData.forEach(function(bubbleDataItem){ //Draws the 25 circles with the stored x and y values
            ctx.arc(bubbleDataItem.x, bubbleDataItem.y, 20, 0, 2* Math.PI); // fillRect post setting size
            ctx.fill();
        })

    }

    draw();

function update(deltaTime) {
    if(!deltaTime) return;

    bubbleData.forEach(function(bubbleDataItem){
    bubbleDataItem.x += 4;
});

}



let lastTime = 0;

function gameLoop(timestamp) {
    let deltaTime = timestamp - lastTime;
    lastTime = timestamp;
    ctx.clearRect(0, 0, 800, 600);
   // bubbleData.forEach(function(bblData){ctx.clearRect(bblData.x, bblData.y, 10, 10)})

    bubbleData.forEach(function(bblData){bblData.x += 1; bblData.y -= 1;})

    update(deltaTime);
    draw();

    requestAnimationFrame(gameLoop);
}
gameLoop();

1 Ответ

1 голос
/ 06 ноября 2019

Вам нужно начинать свой путь каждый раз, когда вы создаете новый круг, чтобы вы могли перемещать ctx.beginPath() в свой цикл for следующим образом:

bubbleData.forEach(function(bubbleDataItem) { 
  ctx.beginPath();
  ctx.arc(bubbleDataItem.x, bubbleDataItem.y, 20, 0, 2 * Math.PI); 
  ctx.fill();
});

См. Пример ниже:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var bubbleData = generateBubbles(); //Array the x and y values are stored in
var bubbleDataLength = bubbleData.length;
var bubbledataX = bubbleData[0].x;
var bubbleDataY = bubbleData[0].y;
var currentX;
var currentY;

function generateBubbles() {
  var generatedBubbleData = [];
  var bubbleCount = 0;
  var maxBubbleCount = 25;
  var bubbleX = 0;
  var bubbleY = 0;

  function yCalc() { //Function that returns the y value of each circle
    var currentY;
    var mathRandom = Math.floor(Math.random() * 101);
    if (mathRandom < 21) {
      bubbleY = 600;
    }

    if (mathRandom < 41 && mathRandom > 20) {
      bubbleY = 500;
    }

    if (mathRandom < 61 && mathRandom > 40) {
      bubbleY = 400;
    }

    if (mathRandom < 81 && mathRandom > 60) {
      bubbleY = 300;
    }

    if (mathRandom < 101 && mathRandom > 80) {
      bubbleY = 200;
    }

    return currentY;
  }

  var mathRandom = Math.floor(Math.random() * 101);

  function xCalc() { //Function that returns the x value of each circle
    var currentX;
    if (mathRandom < 26) {
      bubbleX = Math.random() * 150;
    }

    if (mathRandom < 51 && mathRandom > 25) {
      bubbleX = Math.random() * 175;
    }

    if (mathRandom < 76 && mathRandom > 50) {
      bubbleX = Math.random() * 200;
    }

    if (mathRandom > 75) {
      bubbleX = Math.random() * 250;
    }
    return currentX;
  }

  while (bubbleCount < 25) { //Only allows 25 x and y values
    currentX = xCalc();
    currentY = yCalc();


    generatedBubbleData.push({
      x: bubbleX,
      y: bubbleY
    });

    if (bubbleCount <= 25) {
      bubbleCount++;
      mathRandom = Math.floor(Math.random() * 101);
      xCalc();
    }
  }
  return generatedBubbleData;
}

generateBubbles();

function draw() {
  canvas.width = window.innerWidth; // Sets canvas width and doesn't make drawings blurry
  canvas.height = window.innerHeight; // Sets canvas height and doesn't make drawings blurry
  ctx.fillStyle = "red";
  
  bubbleData.forEach(function(bubbleDataItem) { //Draws the 25 circles with the stored x and y values
    ctx.beginPath();
    ctx.arc(bubbleDataItem.x, bubbleDataItem.y, 20, 0, 2 * Math.PI); // fillRect post setting size
    ctx.fill();
  });
  

}

draw();

function update(deltaTime) {
  if (!deltaTime) return;

  bubbleData.forEach(function(bubbleDataItem) {
    bubbleDataItem.x += 4;
  });

}



let lastTime = 0;

function gameLoop(timestamp) {
  let deltaTime = timestamp - lastTime;
  lastTime = timestamp;
  ctx.clearRect(0, 0, 800, 600);
  // bubbleData.forEach(function(bblData){ctx.clearRect(bblData.x, bblData.y, 10, 10)})

  bubbleData.forEach(function(bblData) {
    bblData.x += 1;
    bblData.y -= 1;
  })

  update(deltaTime);
  draw();

  requestAnimationFrame(gameLoop);
}
gameLoop();
<canvas id="canvas" height="400" width="400" style="border: 1px solid black;"></canvas>
...