Using SVG in GWT

后端 未结 8 841
感动是毒
感动是毒 2021-02-05 12:31

I was wondering if it is possible to include SVG content inside a panel (or whatever would work in GWT), be able to add more to the SVG (like add a circle or a curve) programmat

8条回答
  •  梦毁少年i
    2021-02-05 12:44

    I don't entirely understand why, but the createElementNS JavaScript method allows you to create and correctly format xhtml within html.

    Because there is no equivalent in explorer, GWT does not implement createElementNS, but you can with a quick native method :

    private static native Element createElementNS(final String ns, 
            final String name)/*-{
        return document.createElementNS(ns, name);
    }-*/;
    

    It makes sense to put this into an SVGPanel class.

    import com.google.gwt.user.client.Element;
    import com.google.gwt.user.client.ui.ComplexPanel;
    
    public class SVGPanel extends ComplexPanel{
    
        private static final String SVG_NAMESPACE = "http://www.w3.org/2000/svg";
    
        public SVGPanel() {
            setElement(createElementNS(SVG_NAMESPACE, "svg"));
            showcaseSVG(); //Demonstrate that SVG works! Inexplicably!
        }
    
        private void showcaseSVG(){
            Element svgElement = createElementNS(SVG_NAMESPACE, "circle");
            svgElement.setAttribute("cx", "50");
            svgElement.setAttribute("cy", "50");
            svgElement.setAttribute("r", "30");
            getElement().appendChild(svgElement);
        }
    }
    

    This should produce some simple SVG when added to your program. Congratulations! You are now sticking it to the xhtml man.

提交回复
热议问题