HTML Canvas: изменение цвета прозрачного bru sh вызывает изменение всех цветов на холсте - PullRequest
1 голос
/ 04 февраля 2020

Я черпал вдохновение из этого примера кода , поскольку я пытаюсь сделать sh что-то очень похожее, но с дополнительным слоем, который позволяет вам выбрать, какой цвет вы хотите отметить холст с. По какой-то причине все работает должным образом, но когда я выбираю новый цвет и снова рисую (ie. onMouseMove), цвета всех линий, которые я ранее нарисовал, изменились. Большинство ответов stackoverflow говорят, что мне нужно ctx.beginPath(); и / или `ctx.close, но я пробовал это практически во всех разновидностях, которые вы можете придумать. Я использую React здесь и включил все мои методы класса ниже. Любая помощь будет принята с благодарностью!

    // Here we set up the properties of the canvas element.
    const { drawType } = this.props;
    const myCan = document.getElementById('myCan');
    this.canvas.width = myCan.width;
    this.canvas.height = myCan.height;
    this.ctx = this.canvas.getContext('2d');
    this.ctx.lineCap = 'round';
    this.ctx.lineWidth = 12;
    this.ctx.globalAlpha = .5;
  }

  onMouseDown(e) {
    this.ctx.beginPath();
    const { drawType } = this.props;
    this.isPainting = true;
    const path = [];
    path.push(this.getCoord(e));
    this.line.push(path);
  }

  onMouseMove(e) {
    if (!this.isPainting) return;
    this.line[this.line.length - 1].push(this.getCoord(e));
    this.redraw();
  }

  getCoord(e) {
    const { drawType } = this.props;
    const x = e.nativeEvent.offsetX;
    const y = e.nativeEvent.offsetY;
    return [x, y];
  }

  redraw() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    const { drawType } = this.props;
    // Change color of stroke based on prop passed down from parent
    if (drawType == null) { return; }
    this.ctx.strokeStyle = drawType === 'red' ? this.red : null;
    this.ctx.strokeStyle = drawType === 'blue' ? this.blue : null;
    for (let i = 0; i < this.line.length; ++i) {
      const path = this.line[i];
      if (path.length === 0) continue;
      if (path.length === 1) {
        this.ctx.moveTo(path[0][0], path[0][1]);
        this.ctx.lineTo(path[0][0] + 1, path[0][1] + 1);
      } else {
        this.ctx.moveTo(path[0][0], path[0][1]);
        for (let j = 1; j < path.length; ++j) this.ctx.lineTo(path[j][0], path[j][1]);
      }
    }
    this.ctx.stroke();
  }


  endPaintEvent() {
    if (this.isPainting) {
      this.isPainting = false;
    }
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...