Canvas - раздельные 2 массива строк по клику - PullRequest
0 голосов
/ 17 января 2019
  • Кнопка влево - нажимает синие линии с X
  • Кнопка «Вправо» - нажимает на красные линии буквой О
  • Кнопка Удалить - удаляет последнюю строку в массиве

Итак, когда я нажимаю на Левый - синие линии с X вставляются в массив.

Проблема в том, что ... если я нажму вправо и начну добавлять красные линии, синие линии, которые уже нарисованы на холсте, также изменяются на красные линии с буквами O.

Как я могу отделить 2 кнопки, чтобы они не мешали друг другу?

Спасибо.

function drawGrid() {
    ctx.strokeStyle = "black";
    ctx.lineWidth = 0.1;
    ctx.beginPath();
    for (x = 15; x <= w; x += 60) {
        ctx.moveTo(x, 0);
        ctx.lineTo(x, h);
        for (y = 20; y <= h; y += 20) {
            ctx.moveTo(0, y);
            ctx.lineTo(w, y);
        }
    }
    ctx.stroke();
}
var ry = [[]];

var canvas = document.querySelector("#myCanvas");
var w = (canvas.width = 450);
var h = (canvas.height = 280);

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

drawGrid();

// Правая кнопка <------------------------------------------ -------- </p>

document.getElementById('right').onclick = function () {

    ry.push([]);

    myCanvas.addEventListener("click", e => {
        var offset = canvas.getBoundingClientRect();
        var x = e.clientX - offset.left;
        var y = e.clientY - offset.top;
        ry[ry.length - 1].push({ x: x, y: y });
        ctx.clearRect(0, 0, w, h);
        drawGrid();
        drawChart();
    });

    deletes.addEventListener("click", e => {
        if (ry[ry.length - 1].length > 0) {
            ry[ry.length - 1].pop();
        } else {
            ry.pop();
            ry[ry.length - 1].pop();
        }
        ctx.clearRect(0, 0, w, h);
        drawGrid();
        drawChart();
    });


    function drawGrid() {
        ctx.strokeStyle = "black";
        ctx.lineWidth = 0.1;
        ctx.beginPath();
        for (x = 15; x <= w; x += 60) {
            ctx.moveTo(x, 0);
            ctx.lineTo(x, h);
            for (y = 20; y <= h; y += 20) {
                ctx.moveTo(0, y);
                ctx.lineTo(w, y);
            }
        }
        ctx.stroke();
    }

    function drawChart() {
        ctx.lineWidth = 1;
        for (let index = 0; index < ry.length; index++) {
            for (let i = 0; i < ry[index].length; i++) {
                let l = ry[index][i];
                drawCircle(l.x, l.y);
                if (i > 0) {
                    let last = ry[index][i - 1];
                    ctx.beginPath();
                    ctx.moveTo(last.x, last.y);
                    ctx.lineTo(l.x, l.y);
                    ctx.strokeStyle = "red";
                    ctx.stroke();
                }
            }
        }
    }

    function drawCircle(x, y) {
        ctx.beginPath();
        ctx.arc(x, y, 6, 0, Math.PI * 2);
        ctx.strokeStyle = "red";
        ctx.stroke();
    }

};

// Левая кнопка <------------------------------------------ -------- </p>

document.getElementById('left').onclick = function () {

    ry.push([]);

    myCanvas.addEventListener("click", e => {
        var offset = canvas.getBoundingClientRect();
        var x = e.clientX - offset.left;
        var y = e.clientY - offset.top;
        ry[ry.length - 1].push({ x: x, y: y });
        ctx.clearRect(0, 0, w, h);
        drawGrid();
        drawChart();
    });

        function drawGrid() {
        ctx.strokeStyle = "black";
        ctx.lineWidth = 0.1;
        ctx.beginPath();
        for (x = 15; x <= w; x += 60) {
            ctx.moveTo(x, 0);
            ctx.lineTo(x, h);
            for (y = 20; y <= h; y += 20) {
                ctx.moveTo(0, y);
                ctx.lineTo(w, y);
            }
        }
        ctx.stroke();
    }

    function drawChart() {
        ctx.lineWidth = 1;
        for (let index = 0; index < ry.length; index++) {
            for (let i = 0; i < ry[index].length; i++) {
                let l = ry[index][i];
                drawCross(l.x, l.y);
                if (i > 0) {
                    let last = ry[index][i - 1];
                    ctx.beginPath();
                    ctx.moveTo(last.x, last.y);
                    ctx.lineTo(l.x, l.y);
                    ctx.strokeStyle = "blue";
                    ctx.stroke();
                }
            }
        }
    }

    function drawCross(x, y) {

        ctx.beginPath();
        ctx.moveTo(x - 6, y - 6);
        ctx.lineTo(x + 6, y + 6);

        ctx.moveTo(x + 6, y - 6);
        ctx.lineTo(x - 6, y + 6);
        ctx.strokeStyle = "blue";
        ctx.stroke();
    }

};

1 Ответ

0 голосов
/ 17 января 2019

Приятно знать, что вы можете вызывать функцию как оконный метод. Например, если у вас есть function test(), вы можете вызвать эту функцию как window["test"]()

В вашем случае внутри функции drawChart() вы можете вызвать либо drawCircle(), либо drawCross()

Когда я помещаю точки в массив точек, кроме x и y, я добавляю f (для функции). Значение f представляет собой строку с именем функции: drawCircle или drawCross

Внутри функции drawChart вы найдете следующую строку кода: window[l.f](l.x, l.y) Это вызывает либо drawCircle(), либо drawCross() в зависимости от значения l.f: имя функции.

Имя функции - это глобальная переменная, объявленная в начале моего кода и для которой установлено drawCircle: let theFunction = "drawCircle";

Вы меняете значение theFunction при нажатии правой или левой кнопки.

//this is an array of arrays
//when I click on the canvas a new point is pushed on the last array of this array
var ry = [[]];

var canvas = document.querySelector("#myCanvas");
let w = (canvas.width = 450);
let h = (canvas.height = 280);

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

let theFunction = "drawCircle";

drawGrid();


function drawCircle(x, y) {
  ctx.beginPath();
  ctx.arc(x, y, 6, 0, Math.PI * 2);
  ctx.strokeStyle = "red";
  ctx.stroke();
}

 function drawCross(x, y) {
   ctx.beginPath();
   ctx.moveTo(x - 6, y - 6);
   ctx.lineTo(x + 6, y + 6);

   ctx.moveTo(x + 6, y - 6);
   ctx.lineTo(x - 6, y + 6);
   ctx.strokeStyle = "blue";
   ctx.stroke();
}


myCanvas.addEventListener("click", e => {
  var offset = canvas.getBoundingClientRect();
  var x = e.clientX - offset.left;
  var y = e.clientY - offset.top;
  //a new point is pushed on the last array of ry
  ry[ry.length - 1].push({ x: x, y: y, f:theFunction });
  // delete everything
  ctx.clearRect(0, 0, w, h);
  // draw everything
  drawGrid();
  drawChart();
});

sterge.addEventListener("click", e => {
  //when sterge is clicked the last point from the last array is deleted
  if (ry[ry.length - 1].length > 0) {
    ry[ry.length - 1].pop();
  } else {
    //if the last array is empty I delete this array 
    ry.pop();
    //and then I delete the last point from the last array
    ry[ry.length - 1].pop();
  }
  // delete everything
  ctx.clearRect(0, 0, w, h);
   // draw everything
  drawGrid();
  drawChart();
});

dreapta.addEventListener("click", e => {
  theFunction = "drawCircle"
  //when dreapta is clicked, a new array is pushed into the ry
  ry.push([]);
});

stanga.addEventListener("click", e => {
  theFunction = "drawCross"
  //when dreapta is clicked, a new array is pushed into the ry
  ry.push([]);
});

function drawGrid() {
  ctx.strokeStyle = "black";
  ctx.lineWidth = 0.1;
  ctx.beginPath();
  for (x = 15; x <= w; x += 60) {
    ctx.moveTo(x, 0);
    ctx.lineTo(x, h);
    for (y = 20; y <= h; y += 20) {
      ctx.moveTo(0, y);
      ctx.lineTo(w, y);
    }
  }
  ctx.stroke();
}

function drawChart() {
  ctx.lineWidth = 1;
  // for every array in the ry array
  for (let index = 0; index < ry.length; index++) {
    // for every point in the ry[index]
    for (let i = 0; i < ry[index].length; i++) {
      let l = ry[index][i];
      // draw the circle or the cross
      window[l.f](l.x, l.y)
      // draw the line
      if (i > 0) {
        let last = ry[index][i - 1];
        ctx.beginPath();
        ctx.moveTo(last.x, last.y);
        ctx.lineTo(l.x, l.y);
        ctx.strokeStyle = "blue";
        ctx.stroke();
      }
    }
  }
}
<canvas id="myCanvas"></canvas>
<p><input type="button" value="dreapta" id="dreapta" /> 
<input type="button" value="stanga" id="stanga" />   
<input type="button" value="sterge" id="sterge" />
</p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...