javajavafxcanvasgraphicscontext

How to clear an inclined rectangle in JavaFX Canvas efficiently?


Currently I have the following problem: I would like to draw a straight angled line in JavaFX Canvas like so (Recalling from memory so method names might not be accurate):

Canvas canvas = new Canvas(500, 600);

GraphicsContext gc = canvas.getGraphicsContext2D();

gc.setStroke(Color.GREEN);

gc.setLineWidth(5.0);

gc.strokeLine(10, 10, 200, 200);

Now when I want to clear this line, I could obviously clear the entire Canvas using gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight()); but that is clearing the entire canvas including other lines and points I may want to keep. Say, for example I have created a new point after the line: gc.strokeOval(50, 20, 5, 5); How would I in one step clear only the line and not the point?

Having googled the problem already, I didn't find anything about exactly this. I am kind of expecting it just doesn't work but maybe some of you might find a workaround for this.

I already tried searching for another method in GraphicsContext but were unsuccessful.


Solution

  • Based on the comments on the question, this may be the answer:

    gc.setStroke(backgroundColor);
    gc.strokeLine(10, 10, 200, 200);
    gc.setStroke(Color.GREEN)
    

    This clears the line by drawing the same line in the backgroundColor over it, effectively removing it.