1

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!

2 Answers2

3

First of all, to draw rect on drag (or mouse move), you just clear the canvas, and draw a new rect. Second of all, canvas shapes are not object, so you can't interact with them as far as I know, if you want interactivity, consider using svg. Here is a sloppy implementation of drawing on dragging.

 $("canvas").mousedown(function(event){
     var ctx = this.getContext("2d");
     ctx.clearRect(0,0,$(this).width(),$(this).height());
     var initialX = event.clientX - this.getBoundingClientRect().left;
     var initialY = event.clientY - this.getBoundingClientRect().top;

     $(this).mousemove(function(evt) {
         ctx.strokeRect(initialX, initialY, evt.clientX - event.clientX, evt.clientY - event.clientY);
     });
 });
Trash Can
  • 6,608
  • 5
  • 24
  • 38
  • you should also remove the event listener, if not after 20 rectangles, it will draw the same rect 20 times :P – cancerbero Aug 29 '19 at 10:28
3

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!

Community
  • 1
  • 1
traktor
  • 17,588
  • 4
  • 32
  • 53