Как создать несколько фигур на холсте при перетаскивании мышью и сделать так, чтобы они перекрывали друг друга? - PullRequest
0 голосов
/ 06 января 2020

Внутри элемента canvas я хочу иметь возможность рисовать несколько прямоугольников при перетаскивании мышью (как влево, так и вправо). Пока у меня есть следующее:

class Waveform {
  constructor(container_selector) {
    this.render(container_selector)
  }

  render(container_selector) {
    this.canvas = document.querySelector(container_selector)
    this.canvas.width = 800
    this.canvas.height = 150
    this.canvas.style.border = '1px solid black'
    this.ctx = this.canvas.getContext('2d')
    this.ctx.fillStyle = 'rgba(200, 0, 0, 0.7)'

    this.canvas.addEventListener('mousedown', this.mouseDown)
    this.canvas.addEventListener('mousemove', this.mouseMove)
    this.canvas.addEventListener('mouseup', this.mouseUp)
  }

  mouseDown = e => {
    this.drag = true
    this.rect = {}
    this.rect.x = e.clientX - this.canvas.offsetLeft
    this.rect.y = 0
    this.rect.w = 1
    this.rect.h = this.canvas.height
    this.ctx.fillRect(
      this.rect.x,
      this.rect.y,
      this.rect.w,
      this.rect.h,
    )
  }

  mouseMove = e => {
    if (this.drag) {
      this.ctx.clearRect(this.rect.x, this.rect.y, this.rect.w, this.rect.h)
      this.rect.w = (e.clientX - this.canvas.offsetLeft) - this.rect.x;
      this.ctx.fillRect(
        this.rect.x,
        this.rect.y,
        this.rect.w,
        this.rect.h,
      )
    }
  }

  mouseUp = e => {
    this.drag = false
  }
}

let waveform = new Waveform('#waveform')
<html>

<head>
</head>

<body>
  <canvas id="waveform"></canvas>
</body>

</html>

Проблема с этим кодом заключается в том, что когда я перетаскиваю прямоугольник над уже существующим, часть существующего стирается. Я понимаю, почему это так, но я хочу, чтобы прямоугольники перекрывались , чтобы два (или более) могли существовать одновременно. Как этого добиться?

1 Ответ

0 голосов
/ 06 января 2020

Вот решение, где я удалил вашу строку clearReact.

class Waveform {
  constructor(container_selector, logger_selector) {
    this.rects = []
    this.logger = new Logger(logger_selector)
    this.render(container_selector)
  }

  render(container_selector) {
    this.canvas = document.querySelector(container_selector)
    this.canvas.width = 800
    this.canvas.height = 150
    this.canvas.style.border = '1px solid black'
    this.ctx = this.canvas.getContext('2d')
    this.ctx.fillStyle = 'rgba(200, 0, 0, 0.7)'

    this.canvas.addEventListener('mousedown', this.mouseDown)
    this.canvas.addEventListener('mousemove', this.mouseMove)
    this.canvas.addEventListener('mouseup', this.mouseUp)
  }

  mouseDown = e => {
    this.drag = true
    this.rect = {}
    this.rect.x = e.clientX - this.canvas.offsetLeft
    this.rect.y = 0
    this.rect.w = 1
    this.rect.h = this.canvas.height
    this.ctx.fillRect(
      this.rect.x,
      this.rect.y,
      this.rect.w,
      this.rect.h,
    )
  }

  mouseMove = e => {
    if (this.drag) {
      this.rect.w = (e.clientX - this.canvas.offsetLeft) - this.rect.x;
      this.ctx.fillRect(
        this.rect.x,
        this.rect.y,
        this.rect.w,
        this.rect.h,
      )
    }
  }

  mouseUp = e => {
    this.drag = false
    this.rects.push(this.rect)
    this.logger.add(this.rect)
  }
  
  getRects() {
    return this.rects
  }
}

class Logger {
  constructor(container_selector) {
    this.list = document.querySelector(container_selector)
  }
  
  add(obj) {
    let li = document.createElement("li")
    li.textContent = JSON.stringify(obj)
    this.list.appendChild(li)
  }
}

let waveform = new Waveform('#waveform', '#list')
<html>

<head>
</head>

<body>
  <canvas id="waveform"></canvas>
</body>

<ul id="list">
</ul>

</html>

Я предлагаю вам изменить цвет заливки для каждого прямоугольника, который вы вставляете в свой холст.

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