Search code examples
javascripthtmlcanvashtml5-canvasrectangles

Javascript Canvas - Draw rectangle drag and drop


I want to be able to click and drag to draw a rectangle on a javascript canvas.

I need to be able to see the rectangle as I'm dragging to change size as I'm dragging like a "rubber band" as I've heard it been called. And then it creates on mouseup.

I'm having serious difficulties with this, any help is appreciated, thanks!


Solution

  • An algorithm to investigate would be to

    1. Use animation frame callback to clear and write a new rectangle to the canvas. ( See requestAnimationFrame )

    2. Use mousedown and mouseup events over the canvas to initiate tracking mouse movement. The mousedown event could start animation calls to draw a 1x1 pixel rectangle.

    3. mousemove events record the position of the mouse for use by animation frame drawing code - and may call requestAnimationFrame if no callback is pending.

    4. If you can clear the canvas of previous content to create the rubber band effect, the last drawn rectangle on mouseup is the result.

    5. If existing content needs to be preserved, investigate making a copy of the canvas on mousedown, and copying it back to the canvas before drawing new rectangles. See questions like how to copy a canvas locally and/or how to (deep) clone a canvas

    Happy coding, there's a lot to learn!