GWT Canvas2D draw Image

Go To StackoverFlow.com

4

/**
 * This is the entry point method.
 */
public void onModuleLoad() {
    Canvas canvas = Canvas.createIfSupported();
    final Context2d context2d = canvas.getContext2d();

    RootPanel.get("canvas").add(canvas);
    Image img = new Image("face.png");
    final ImageElement face = ImageElement.as(img.getElement());
    img.addLoadHandler(new LoadHandler() {

        @Override
        public void onLoad(LoadEvent event) {
            context2d.drawImage(face, 0, 0);
        }
    });
    //RootPanel.get("canvas").add(img);
}

This is my code. I want to draw the image onto the canvas. This works if the last line:

RootPanel.get("canvas").add(img);

is NOT commented out.

But with the line commented it seems that the image wont be loaded or so. Any ideas?

2012-04-03 20:30
by Basic Coder


3

Have you placed the image within the WEB-INF folder? That's where GWT loads the images from. Normally it's recommend to create an "images" folder so you can load it with "images/face.png".

2012-05-09 03:27
by Stephane Grenier


5

The Image widget has to be added to the page to trigger image load. Just make it invisible:

public void onModuleLoad() {    
    Canvas canvas = Canvas.createIfSupported();
    final Context2d context2d = canvas.getContext2d();

    RootPanel.get().add(canvas);
    Image img = new Image("face.png");
    final ImageElement face = ImageElement.as(img.getElement());
    img.addLoadHandler(new LoadHandler() {

        @Override
        public void onLoad(LoadEvent event) {
            context2d.drawImage(face, 0, 0);
        }
    });

    img.setVisible(false);
    RootPanel.get().add(img);
}        
2013-06-04 16:40
by kjohnson
This worked for me, except I had to put the img.setVisible(false); inside the onLoad - Craigo 2016-03-16 04:10


0

You can use an image loader, such as: http://code.google.com/p/google-web-toolkit-incubator/wiki/ImageLoader.

2012-04-03 20:50
by fgb