Virgilio K
Virgilio K

Reputation: 53

JavaFX: how to clear a drawing without affecting background

Very simple question, but I could not find the answer in JavaFX docs or StackOverflow:

I have a JavaFX Canvas filled with a graph (various calls to strokeLine(), not the issue here). I need to be able to draw a rectangle over this graph, then simply clear the rectangle, without affecting the graph in the background. (Like an undo operation).

Code to draw the rectangle ('p' and 'e' are points):

gc.rect(p.getX(), p.getY(), e.getX()-p.getX(), e.getY()-p.getY());
gc.stroke();

The most obvious answer would be to use the clearRect() method, but the problem is that it clears also the portion of the graph in the background...

So the question is: how do I clear a drawing that was made with stroke(), without affecting the other drawings in the background?

Upvotes: 1

Views: 2394

Answers (3)

FlickIt
FlickIt

Reputation: 71

This can be acheaved by taking snapshot(s) of your Canvas, using the .snapshot(SnapshotParameters params, WritableImage image) method. Basicly, every time you draw something on your Canvas, you take a snapshot of it and store it somewhere (for example in a ArrayList). Then you can use those snapshots to create a 'undo' operation, by using the . drawImage(Image img, double x, double y) method of Canvas's GraphicsContext, in which you would pass the snapshot you want to go back to as the Image parameter.

Upvotes: 0

mipa
mipa

Reputation: 10650

It might be more straight forward and much more the JavaFX-way of doing things if you just put your canvas into a Group and then just add a Rectangle node to the Group which you can remove at any time if you want.

Upvotes: 1

user43968
user43968

Reputation: 2129

You can't do this with one canvas.

Canvas only store the result of your painting operation. This is the interest of the canvas you can stroke million times the same line and it will only store and represent the result and doesn't consume more memory.

So you if you need to draw Something over your chart you should put an other canvas over the chart and draw on the second canvas.

Upvotes: 4

Related Questions