GWT Canvas - 保存图像并打开它

时间:2012-07-18 14:44:33

标签: html5 gwt canvas html5-canvas

我将图像保存在字符串中,然后当我打开它时,它总是300x150

为什么图像会被截断?

300x150来自哪里?

代码就是你所看到的。只需2个按钮。

第一个将图像保存在“png”中,另一个从“png”中读取图像

                    Button save = new Button("copy");
                    save.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                            ImageElement imageElement = ImageElement.as(image.getElement());

                            Canvas canvasTmp = Canvas.createIfSupported();
                            Context2d context = canvasTmp.getContext2d();
                            context.drawImage(imageElement, 0.0, 0.0, imageElement.getWidth(), imageElement.getHeight());
                            png = canvasTmp.toDataUrl("image/png");
                        }
                    });

                    Button open = new Button("open");
                    open.addClickHandler(new ClickHandler() {

                        @Override
                        public void onClick(ClickEvent event) {

                            final Image image = new Image(png);
                            vp.add(image);
                            image.addLoadHandler(new LoadHandler() {

                                @Override
                                public void onLoad(LoadEvent event) 
                                {
                                    Window.alert("ok");
                                }
                            });

                            image.addErrorHandler(new ErrorHandler() {

                                @Override
                                public void onError(ErrorEvent event) {
                                    Window.alert("error");
                                }
                            } );

                        }
                    });

1 个答案:

答案 0 :(得分:1)

画布的默认宽度为300像素,默认高度为150像素。在创建画布之后和绘制图像之前,请考虑这样做:

int width = imageElement.getWidth()
int height = imageElement.getHeight()
canvasTmp.setWidth(width + "px");
canvasTmp.setHeight(height + "px");
canvasTmp.setCoordinateSpaceWidth(width);
canvasTmp.setCoordinateSpaceHeight(height);