Все мои линии на холсте меняют цвет, когда я меняю одну строку - PullRequest
0 голосов
/ 26 января 2019

Мне нравится создавать линии, которые рисуются автоматически, и я хотел бы, чтобы они возвращались в середину и меняли цвет, когда он выходит из размера холста.Все сделано, хорошо возвращается в середину и хорошо меняет цвет.Но маленькая проблема!Все мои линии, которые уже были нарисованы до этого, меняются на один и тот же цвет .... Я искал час без решения ^^

Можете ли вы мне помочь?

Вотчасти моего кода, которые я считаю наиболее важными для этой проблемы:

Вот моя строка!

function Line(x0, y0, x1, y1, color) {
              this.x0 = x0;
              this.y0 = y0;
              this.x1 = x1;
              this.y1 = y1;
              this.color = color;
              this.draw = function() {
                ctx.strokeStyle = this.color;
                ctx.moveTo(this.x0, this.y0,)
                ctx.lineTo(this.x1, this.y1);
                ctx.stroke();
              }
            } 

Есть моя функция для создания строки!

var x = cx;
var y = cy;
var color = randomColor();
var lines = [];

function loop() {
    var newx = randomPoint(x, 100);
    var newy = randomPoint(y, 100);
    var line = new Line(x, y, newx, newy, color);
    x = newx;
    y = newy;

    lines.push(line);

    if(x > canvas.width || y > canvas.height || x < 0 || y < 0) {
        x = cx;
        y = cy;
        color = randomColor();
    }

    lines[0].draw();
    lines = [];

    time = setTimeout(loop, 50);
}

1 Ответ

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

Вам нужно добавить ctx.beginPath() вверху вашей функции draw:

class Line {
  constructor(x0, y0, x1, y1, color) {
    this.x0 = x0;
    this.y0 = y0;
    this.x1 = x1;
    this.y1 = y1;
    this.color = color;
  }
  
  draw(ctx) {
    ctx.beginPath();
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 4;
    ctx.moveTo(this.x0, this.y0);
    ctx.lineTo(this.x1, this.y1);
    ctx.stroke();
  }
} 

function randomColor() {
  return ['red', 'green', 'blue', 'yellow', 'cyan', 'magenta'][Math.random() * 6 | 0];
}

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = window.innerWidth;
const maxHeight = window.innerHeight;
const cx = maxWidth / 2 | 0;
const cy = maxHeight / 2 | 0;

canvas.width = maxWidth;
canvas.height = maxHeight;

let counter = 0;
let x0 = cx;
let y0 = cy;
let color = randomColor();

function drawLine() {
    const x1 = x0 + Math.random() * 200 - 100;
    const y1 = y0 + Math.random() * 200 - 100;
    
    new Line(x0, y0, x1, y1, color).draw(ctx);
    
    x0 = x1;
    y0 = y1;

    if (x0 < 0 || y0 < 0 || x0 > maxWidth || y0 > maxHeight) {
        x0 = cx;
        y0 = cy;
        color = randomColor();
    }
    
    if (++counter > 500) {
      clearInterval(intervalID);
    }
}

const intervalID = setInterval(drawLine, 100);
body {
  margin: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

#canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canvas"></canvas>

Однако обратите внимание, что при таком подходе соединения между различными отрезками линий не выглядят непрерывными (чем резче соединение, тем более очевидно это), поэтому вы можете предпочесть создание нового пути только при изменении цвета и вернуться в центр:

const COLORS = ['red', 'green', 'blue', 'yellow', 'cyan', 'magenta'];
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const maxWidth = window.innerWidth;
const maxHeight = window.innerHeight;
const cx = maxWidth / 2 | 0;
const cy = maxHeight / 2 | 0;

canvas.width = maxWidth;
canvas.height = maxHeight;
ctx.lineWidth = 4;
ctx.lineJoin = 'round';

let counter = -1;
let currentColor = -1;
let x = -1;
let y = -1;

function drawLines() {
  if (x < 0 || y < 0 || x > maxWidth || y > maxHeight) {
    ctx.beginPath();
    ctx.strokeStyle = COLORS[currentColor = (currentColor + 1) % COLORS.length];
    ctx.moveTo(x = cx, y = cy);
  }

  x += Math.random() * 200 - 100;
  y += Math.random() * 200 - 100;

  ctx.lineTo(x, y);
  ctx.stroke();

  if (++counter === 500) {
    clearInterval(intervalID);
  }
}

const intervalID = setInterval(drawLines, 100);
body {
  margin: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

#canvas {
  width: 100%;
  height: 100%;
}
<canvas id="canvas"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...