1

Sorry if the title is rather confusing, but I'm drawing a rectangle to a canvas in AngularJS and I'd like the user to be able to click on a point, and while mousedown is fired, the rectangle can be dragged to its final position until mouseup is fired. My code works for the most part, except that there is no way to clear the rectangle at the last position and so the end result is lot of rectangles being drawn instead of one final product. This is some code on the issue, however, I didn't include the eventlisteners for mouseup and mousedown b/c those are rather self-explanatory, work as needed, and unrelated to the problem.

    element.bind('mousemove', function(event){

        if(drawing){
            // get current mouse position
            if(event.offsetX!==undefined){
                currentX = event.offsetX;
                currentY = event.offsetY;
            } else { //firefox
                currentX = event.layerX - event.currentTarget.offsetLeft;
                currentY = event.layerY - event.currentTarget.offsetTop;
            }

            rect.style.width = (currentX - startX) + 'px';
            rect.style.height = (currentY - startY) + 'px';

            //draw the rectangle using context
            draw(startX, startY, currentX - startX, currentY - startY);

        }
    });

    function draw(aX, aY, bX, bY){
        //this is where I'm drawing too many rectangles!!
        ctx.beginPath();
        ctx.lineWidth="2";
        ctx.strokeStyle="red";
        ctx.strokeRect(aX,aY,bX,bY);
    }

NOTE: This post gives a good overview of the problem, except that it is not javascript

Community
  • 1
  • 1
Daniel Jamrozik
  • 1,228
  • 2
  • 11
  • 25

1 Answers1

0

The process is as follows:

  • At mouse down, store the background to a temp canvas, draw rectangle to main
  • At mouse move, redraw background from temp, redraw rectangle on main
  • At mouse up, redraw background from temp, loose the temp

In compiled languages you could benefit by optimizing storing only the lines for the rectangle, but with JavaScript the benefit will be eaten by the overhead of extra code so we might as well just draw the background in a single operation and let the browser take the main work.

You can optimize by only drawing a region from the stored background representing the draw rectangle.

If you don't want to store a copy of the canvas you can optionally render the background from scratch. This is a viable option if memory becomes a concern, at the cost of performance.