Холст рисует один раз с переводом и один раз без ошибок - PullRequest
0 голосов
/ 23 апреля 2019

Я принял почти все возможные контрмеры, чтобы моя программа не рисовала две точки вместо одной на моем графике. Я хочу, чтобы точка в центре была показана, а не та, что вверху слева. Мне кажется, что точка рисуется один раз в верхнем левом углу, совпадая с координатами и всем остальным, но затем она рисует вторую точку с помощью метода translate. Конечно, это всего лишь предположение о том, что происходит на экране. Проблема возникает где-то в функции draw(), init() или anim() - я не могу точно определить, где проблема.

let graph = document.getElementById('chart');
let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;

function algebra() {

  xVertex = 2 * 10;
  yVertex = 5 * 10;

  let radius = 3;
  let node = [];


  function Node(xVertex, yVertex, radius) {
    this.r = radius;
    this.xV = xVertex;
    this.yV = yVertex;

    this.draw = function() {
      c.beginPath();
      c.arc(this.xV, this.yV, this.r, 0, Math.PI * 2, false);
      c.fillStyle = "red";
      c.fill();
      c.translate(377, 377);
      c.stroke();
      c.closePath();
    };

    this.update = function() {
      this.draw();

    };
  };

  function init() {
    node.push(new Node(xVertex, yVertex, radius));
    anim();
  };

  function anim() {
    requestAnimationFrame(anim);
    for (let i = 0; i < node.length; i++) {
      node[i].update(node);
    };
    c.clearRect(0, 0, graph.width, graph.height);
    console.log(node);
  };
  init();
};
#graph {
  left: 100px;
  background-color: grey;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title> Proof of concept </title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div id="graph">
    <canvas id="chart"></canvas>
    <div id="y-axis"></div>
    <div id="x-axis"></div>
  </div>
  <div id="button" onclick="algebra()">
    <div id="btext">Calculate</div>
  </div>

  <script type="text/javascript" src="app.js"></script>
</body>

</html>

1 Ответ

0 голосов
/ 23 апреля 2019

Кажется, я нашел ваши ошибки:

1) При вызове anim() сначала необходимо очистить холст, а затем перерисовать все точки.

2) Вызвать следующий кадр анимации после того, как все точки нарисованы на холсте

И главная проблема:

3) Вы выполняете перевод источника холста на каждую нарисованную точку (и большую (377, 377)). Так как источник меняется на каждой итерации или нарисованной точке, также перемещается удаляемая часть холста. Два очка, которые вы получили, были первым и вторым итерарионами, остальные были за кадром.

Что вам нужно сделать, это перевести начало холста в его середину только один раз, сразу после:

let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;

//Translate the origin to the canvas' center (do this only once)
c.translate(graph.width/2, graph.height/2);

Если источник холста переместился в центр, вы также должны стереть холст с -width / 2 до width / 2 и height / 2 до height / 2. Для этого вы должны использовать:

c.clearRect(-graph.width/2, -graph.height/2, graph.width, graph.height);

Просто для забавы , я добавил еще три точки в массив узлов и добавил случайное число от -1 до 1 к каждой координате в каждой итерации. Это приводит к броуновскому моделированию движения.

let graph = document.getElementById('chart');
let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;

//Translate the origin to the canvas' center (do this only once)
c.translate(graph.width/2, graph.height/2);


function algebra() {

  //Changed to 0 to plot at center
  xVertex = 0;
  yVertex = 0;

  let radius = 3;
  let node = [];


  function Node(xVertex, yVertex, radius) {
    this.r = radius;
    this.xV = xVertex;
    this.yV = yVertex;

    this.draw = function() {      
      c.beginPath();
      c.arc(this.xV, this.yV, this.r, 0, Math.PI * 2, false);
      c.fillStyle = "red";
      c.fill();
      c.stroke();
      c.closePath();
    };

    this.update = function() {
      //this will generate random movement in x and y.
      this.xV += Math.random()*2-1;
      this.yV += Math.random()*2-1;
      this.draw();
    };
  };

  function init() {
    node.push(new Node(xVertex, yVertex, radius));
    node.push(new Node(xVertex, yVertex, radius));
    node.push(new Node(xVertex, yVertex, radius));
    node.push(new Node(xVertex, yVertex, radius));
    anim();
  };

  function anim() {
    //First clear the canvas then redraw
    c.clearRect(-graph.width/2, -graph.height/2, graph.width, graph.height);
    for (let i = 0; i < node.length; i++) {
      node[i].update(node);
    };
    //After all are drawn, call the next Animation Frame
    requestAnimationFrame(anim);
  };
  init();
};
#graph {
  left: 100px;
  background-color: grey;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title> Proof of concept </title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div id="graph">
    <canvas id="chart"></canvas>
    <div id="y-axis"></div>
    <div id="x-axis"></div>
  </div>
  <div id="button" onclick="algebra()">
    <div id="btext">Calculate</div>
  </div>

  <script type="text/javascript" src="app.js"></script>
</body>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...