开发者

draw a circle using html5 canvas in gwt?

I want to draw a circle in GWT, with some mouse over and drag-and-drop support. Is it possible to do so in GWT? can you p开发者_如何学Crovide an example code?


Yes you can. The pseudo code will be something like this -

Canvas canvas = Canvas.createIfSupported();
Context2d context=canvas.getContext2d();
RootPanel.get(A_HOLDER_DIV_ID).add(canvas);

Add Handlers as follows -

1) Mouse down handler to get the start of the drag

canvas.addMouseDownHandler() - 
//catch the start of the circle drag, 
//clear the canvas
//Note the startx & starty

1) Mouse up handler to get the end the start of the drag

canvas.addMouseUpHandler() - 
//catch the end of the circle drag, 
//mark dragging as stopped

3) Mouse move handler to create the circle

canvas.addMouseMoveHandler() - 
//if drag started through event 1 then - 
//get x & y;
//calculate centre of circle and radius based on startx, starty and x & y above
//Clear the canvas
//And add the following code

context.setFillStyle(color);
context.beginPath();
context.arc(calculatedCenterx, calculatedCentery, radius, 0, Math.PI * 2.0, true);
context.closePath();
context.fill();

EDIT - Take a look at this good example on how to get started with GWT HTML5 canvas


That is one approach. The other is to use a framework such as Lienzo which abstracts all that code. You get events, animations, and transformations out the box. Lienzo is a graphics toolkit in Java implemented using GWT, targeting HTML5's canvas. Lienzo is Apache 2, so it is free for all.

To do a circle using Lienzo, you would do something like:

Circle circle = new Circle(radius);
circle.setX(xCoord);
circle.setY(yCoord);
circle.setDraggable(true);
circle.addNodeMouseClickHandler(new NodeMouseClickHandler() {
    @Override
    public void onNodeMouseClick(NodeMouseClickEvent event) {
        ...
    }
});

There are more events you can listen to, but that one is the most common.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜