Hello, I currently have an empty canvas implemented and an example event listener that will create a Div and display an alert when the user clicks on the canvas. However, how should I go about transforming this code so that instead of just creating a new Div when clicked, the user can drag and draw boxes and when the mouse is released, the box is drawn onto the canvas.
MainLayout.java:
package com.vaadin.starter.beveragebuddy.backend;
import com.vaadin.flow.component.dependency.HtmlImport;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.html.NativeButton;
import com.vaadin.flow.router.Route;
import com.vaadin.starter.beveragebuddy.ui.components.Canvas;
import com.vaadin.starter.beveragebuddy.ui.components.CanvasRenderingContext2D;
@HtmlImport("frontend://styles/shared-styles.html")
@Route("")
//@Viewport("width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes")
public class MainLayout extends Div {
private Canvas canvas;
public MainLayout(){
H2 title = new H2("Annotation UI");
title.addClassName("main-layout__title");
canvas = new Canvas(1580, 700);
Div buttons = new Div();
buttons.add(new NativeButton("Select Dataset"));
buttons.add(new NativeButton("Save Annotations"));
buttons.add(new NativeButton("Previous Picture"));
buttons.add(new NativeButton("Next Picture"));
add(canvas, buttons);
}
}
Canvas.java:
package com.vaadin.starter.beveragebuddy.ui.components;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasSize;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.dom.Element;
import com.vaadin.flow.dom.ElementFactory;
@Tag("canvas")
@SuppressWarnings("serial")
public class Canvas extends Component implements HasStyle, HasSize {
private CanvasRenderingContext2D context;
private Element element;
public Canvas(int width, int height) {
context = new CanvasRenderingContext2D(this);
element = getElement();
element.getStyle().set("border", "1px solid");
getElement().setAttribute("width", String.valueOf(width));
getElement().setAttribute("height", String.valueOf(height));
element.addEventListener("mousedown", event -> { // Create a Div on Click
Element boundingBoxResult = ElementFactory.createDiv();
element.appendChild(boundingBoxResult);
// if (isDrawing = true) {
// context.beginPath();
// context.strokeRect(point.getX(), point.getY(), );
// context.fill();
// }
element.getNode().runWhenAttached(ui -> {
ui.getPage().executeJavaScript(String.format("window.alert('%d')", element.getChildCount()));
});
});
}
}
Any help is really much appreciated, thank you!