Shai Almog
Shai Almog

Reputation: 52760

Is it possible to use JavaFX's PerspectiveTransform with the new Canvas class?

We have a lot of Swing code that relies on the graphics semantics for paint, so migrating to JavaFX's hierarchy is not an option (it would be simpler to rewrite to native code/OpenGL). We would like to have support for PerspectiveTransform and the new Canvas class looks interesting.

Is it possible to use the PerspectiveTransform effect with the Canvas class and apply it to elements within?

I know I can probably apply perspective to the entire canvas but I'd like to apply this just to a few elements that I'm drawing (similarly to the way an affine transform is applied in Java2D).

Upvotes: 1

Views: 554

Answers (1)

jewelsea
jewelsea

Reputation: 159291

PerspectiveTransform can only be applied to a canvas as a whole and not to elements inside a Canvas.

The PerspectiveTransform effect works on a node. While the canvas itself is a node, instructions for drawing into the canvas itself are not nodes.

The canvas allows you to set an affine transform which will be applied to subsequent drawing instructions for the canvas, but a perspective transform is a non-affine transform, so that won't help you.

Some alternate options (which may or may not work well for your case):

  1. Layer multiple canvas elements on top of each other, with different perspective transform effects applied to each layer (which is kind of inconvienient). Oracle provide a canvas layering sample.
  2. Apply the math for the perspective transform on each of the co-ordinates you want to plot in your canvas before you actually send them to the canvas.
  3. Use a true 3D surface and co-ordinates instead of the faux 3D provided by PerspectiveTransform, then JavaFX will take care of performing the correct perspective transform calculations for you. If necessary, the 3D surfaces can be placed in a SubScene layered on top of canvas or other nodes.

If you are interested in porting code from a AWT/Swing Graphics2D to a JavaFX GraphicsContext, the following question may be useful: Interoperability between Graphics2D and GraphicsContext.

Upvotes: 1

Related Questions