How to make an overlay on top of JavaFX 2 webview?

后端 未结 2 462
广开言路
广开言路 2020-12-09 22:27

Is it possible to to overlay any JavaFx2 widgets or canvas on top of a JavaFX 2 webview?

I want to generate a transparent heatmap by means of JavaFX 2 on top of a w

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 23:18

    Adding overlay is very easy: just put webview and any pane to StackPane.

    Another story is to synchronize overlay and webview data. To achieve that you need to ask webview for object coordinates through javascript. Here is an example which finds stackoverflow question area and marks it on overlay:

    webView overlay

    public class WebOverlay extends Application {

        @Override
        public void start(Stage stage) {
            StackPane root = new StackPane();
            WebView webView = new WebView();
    
            final WebEngine webEngine = webView.getEngine();
            Canvas overlay = new Canvas(600,600);
            overlay.setOpacity(0.5);
            final GraphicsContext gc = overlay.getGraphicsContext2D();
            gc.setFill(Color.RED);
    
            root.getChildren().addAll(webView, overlay);
            stage.setScene(new Scene(root, 600, 600));
    
            webEngine.getLoadWorker().workDoneProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue.intValue() == 100) {
                    // find coordinates by javascript call
                    JSObject bounds = (JSObject)webEngine.executeScript("document.getElementsByClassName('question-hyperlink')[0].getBoundingClientRect()");
    
                    Number right = (Number)bounds.getMember("right");
                    Number top = (Number)bounds.getMember("top");
                    Number bottom = (Number)bounds.getMember("bottom");
                    Number left = (Number)bounds.getMember("left");
    
                    // paint on overlaing canvas
                    gc.rect(left.doubleValue(), top.doubleValue(), right.doubleValue(), bottom.doubleValue());
                    gc.fill();
                }
            });
            webEngine.load("http://stackoverflow.com/questions/10894903/how-to-make-an-overlay-on-top-of-javafx-2-webview");
    
            stage.show();
        }
    
        public static void main(String[] args) { launch(); }
    }
    

提交回复
热议问题