How to refactor your code?

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

    From this piece of code

    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
            }
        }
    }


    It is necessary to separate the event handler and the function itself.

    something like this
    const mouseDown = () =>{}
    const mouseMove = () =>{}
    const mouseUp = () =>{}
    
    function mouseEvents() {
    canvas.addEventListiner("mousedown", mousedown)
    ....
    }

    helpanite
    JavaScript Anonymous, May 14, 2019

  • 2 Answers
  • 0
    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()
    }
    Anonymous

  • 0
    something like this


    the direction of thought is correct, now do it.



    helpanite


    Come on! you will succeed!
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!