Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a Line with Pen Tool on Canvas Smothly without Having to Redraw All Other Lines

Is there a way to avoid redrawing all the elements on the canvas (so I don't have to keep track of everything), while still having a smooth drawing experience with the currently drawn line?

like image 287
Mia Avatar asked Dec 28 '12 00:12

Mia


1 Answers

This is a very good question, but its worded vaguely. Please be more careful wording questions in the future.

Typically when drawing smooth lines you need to redraw the line from the beginning.

You do not need to redraw everything from the beginning though, because you should be following these operations:

  1. Save the current canvas to an in-memory canvas
  2. Begin drawing a new line
  3. As you're drawing, you are constantly:
    • Clearing the canvas
    • Drawing from in-memory canvas onto main canvas
    • Drawing the line-so-far
  4. When the line finishes, you save the new canvas to the in-memory canvas and repeat this process

The only line you need to keep track of (in terms of points) is the "current" one. All the old lines are saved into the bitmap via the in-memory canvas.

Here's an example I made a long time ago, dealing with smooth lines specifically. The code organization is weird because I started with someone elses code, but it should give you the basic idea:

http://jsfiddle.net/NWBV4/10/

The drawing part described above is seen in the mousemove:

this.mousemove = function(ev) {
    if (tool.started) {
        context.clearRect(0, 0, 300, 300);
        // put back the saved content
        context.drawImage(memCanvas, 0, 0);
        tool.points.push({
            x: ev._x,
            y: ev._y
        });
        drawPoints(context, tool.points);
    }
};
like image 77
Simon Sarris Avatar answered Oct 04 '22 13:10

Simon Sarris