Внутри элемента 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>
Проблема с этим кодом заключается в том, что когда я перетаскиваю прямоугольник над уже существующим, часть существующего стирается. Я понимаю, почему это так, но я хочу, чтобы прямоугольники перекрывались , чтобы два (или более) могли существовать одновременно. Как этого добиться?