Mbreti
@Mbreti
Xa

Как сделать рефакторинг кода?

https://codepen.io/Mbreti/pen/YzqMoEP

Из этого куска кода

const mouseEvent = () => {
    canvas.onmousedown = (e) => {
        const start = { x: e.offsetX, y: e.offsetY };
        canvas.onmousemove = (e) => {
            currPos.x = getXPixelRatio * Math.round((rectPos.x + e.offsetX - start.x) / getXPixelRatio);
            currPos.y = getYPixelRatio * Math.round((rectPos.y + e.offsetY - start.y) / getYPixelRatio);
            currPos.x = edge(currPos.x, 0, w - 25);
            currPos.y = edge(currPos.y, 0, h - 25);         
            renderAll()
            drawRect(currPos.x, currPos.y);
        }
        document.onmouseup = (e) => {
            rectPos.x = currPos.x;
            rectPos.y = currPos.y;
            canvas.onmousemove = null
        }
    }
}


Надо разделить обработчик событие и саму функцию

как-то так
const mouseDown = () =>{}
const mouseMove = () =>{}
const mouseUp = () =>{}

function mouseEvents() {
canvas.addEventListiner("mousedown", mousedown)
....
}

helpanite
  • Вопрос задан
  • 122 просмотра
Решения вопроса 1
Mbreti
@Mbreti Автор вопроса
Xa
const rectPos = { x: 0, y: 0 };
const currPos = { x: 0, y: 0 };
const start= { x: 0, y: 0 };

const handleMouseDown = (e) => {
  start.x = e.offsetX
  start.y = e.offsetY
  canvas.addEventListener('mousemove', handleMouseMove)
  canvas.addEventListener('mouseup', handleMouseUp)
}

const handleMouseMove = (e) => {
  currPos.x = getXPixelRatio * Math.round((rectPos.x + e.offsetX - start.x) / getXPixelRatio);
  currPos.y = getYPixelRatio * Math.round((rectPos.y + e.offsetY - start.y) / getYPixelRatio);
  currPos.x = edge(currPos.x, 0, w - 25);
  currPos.y = edge(currPos.y, 0, h - 25);
  renderAll()
  drawRect(currPos.x, currPos.y);
}

const handleMouseUp = (e) => {
  rectPos.x = currPos.x;
  rectPos.y = currPos.y;
  canvas.removeEventListener('mousemove', handleMouseMove)
  canvas.removeEventListener('mouseup', handleMouseUp)
}

const renderAll = () => {
    ctx.clearRect(0, 0, w, h)
    canvas.addEventListener('mousedown', handleMouseDown)
    renderGrid()
}
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
Robur
@Robur
Знаю больше чем это необходимо
как-то так

направление мысли верное, теперь сделайте это.

helpanite

Давай! у тебя все получится!
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы