Java Reference
In-Depth Information
interior. The
clip()
method clips the
Canvas
by the path, so that future rendering method calls won't have any effect
outside of the path. The
clearRect()
method will clear a rectangular region of the
Canvas
with a transparent color
value. To clear the entire
Canvas
, you can call
clearRect(0, 0, width, height)
.
The following methods serve to provide additional information about the
GraphicsContext
:
•
Canvas getCanvas()
PixelWriter getPixelWriter()
•
boolean isPointInPath(double x, double y)
The
getCanvas()
method returns the
Canvas
object. The
getPixelWriter()
method returns a
PixelWriter
that
can be used to manipulate the
Canvas
on a pixel-by-pixel basis. The
PixelWriter
class is part of the JavaFX Image Ops
API, which we cover in the next subsection. The
isPointInPath()
method returns true if the point
(x, y)
is within
the current path of the
GraphicsContext
.
The program in Listing 10-12 displays a
Canvas
and allows the user to drag the mouse across the screen to draw
an oval. The location and size of the oval is also shown on the
Canvas
.
•
Listing 10-12.
CanvasExample.java
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import static java.lang.Math.abs;
import static java.lang.Math.min;
public class CanvasExample extends Application {
private Point2D p0;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
stage.setTitle("Canvas Example");
stage.setScene(makeScene());
stage.show();
}
private Scene makeScene() {
Canvas canvas = new Canvas(640, 480);
GraphicsContext graphicsContext = canvas.getGraphicsContext2D();
graphicsContext.setFill(Color.BLUE);
graphicsContext.setStroke(Color.RED);
graphicsContext.setFont(Font.font(14));
graphicsContext.strokeText("Click and drag mouse to draw ovals", 20, 20);
Search WWH ::
Custom Search