Reputation: 11422
/**
* 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?
Upvotes: 4
Views: 5588
Reputation: 3717
If you want to avoid needing to add the image to the page to load (which can cause the image to flash up on the page), you can use a native JavaScript load.
package com.mypackage;
public interface Loaded<T> {
public void data(T data);
}
public static native void loadImageNative(String imgBase64, Loaded<ImageElement> loaded) /*-{
var image = new Image();
image.onload = function() {
[email protected]::data(*)(image);
};
image.src = imgBase64;
}-*/;
public void onModuleLoad() {
Canvas canvas = Canvas.createIfSupported();
Context2d context2d = canvas.getContext2d();
String base64Img = MyResouces.myImage().getSafeUri().asString();
RootPanel.get().add(canvas);
loadImageNative(base64Img, imageLoaded -> {
context2d.drawImage(imageLoaded, 0, 0);
});
}
Upvotes: 0
Reputation: 110
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);
}
Upvotes: 4
Reputation: 15927
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".
Upvotes: 3
Reputation: 18569
You can use an image loader, such as: http://code.google.com/p/google-web-toolkit-incubator/wiki/ImageLoader.
Upvotes: 0