I am trying to draw a string at a specific point based on the mouse position (only when I am dragging).
The problem is, that it seems to scale the x and y. When I am at 0,0 with the mouse, the string displays in the right spot, but as I move away, the string draws farther and farther away from my mouse which makes me think there is a hidden scaling thing going on...
I am using event.getX() and the position of the canvas, should I be using some other combination to get the correct mouse position?
below is the code
final Canvas canvas = Canvas.createIfSupported();
final AsyncBool mouseDown = new AsyncBool开发者_运维知识库(false);
final Context2d context = canvas.getContext2d();
context.setFont("bold 8px sans-serif");
canvas.setWidth("100%");
canvas.setHeight("100%");
canvas.addMouseMoveHandler(new MouseMoveHandler() {
@Override
public void onMouseMove(MouseMoveEvent event)
{
if(mouseDown.getBool())
{
context.fillText("Bored.", event.getX() - canvas.getAbsoluteLeft(), event.getY() - canvas.getAbsoluteTop());
}
}
});
canvas.addMouseDownHandler(new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event)
{
mouseDown.setBool(true);
}
});
canvas.addMouseUpHandler(new MouseUpHandler() {
@Override
public void onMouseUp(MouseUpEvent event)
{
mouseDown.setBool(false);
}
});
RootPanel.get().add(canvas);
Your code should work for a canvas which is not resized. But if you resize your canvas, you need to update the canvas coordinate space accordingly as well. For instance, for a 500px, 500px size canvas you can achieve this by :
canvas.setSize("500px","500px");
canvas.setCoordinateSpaceHeight(500);
canvas.setCoordinateSpaceWidth(500);
in your case, you size your canvas using percentage values, you can use :
canvas.setSize("100%","100%");
canvas.setCoordinateSpaceHeight(Window.getClientHeight());
canvas.setCoordinateSpaceWidth(Window.getClientWidth());
since these methods don't accept percentage values, you need to calculate the parent container's width, and height in pixels.
精彩评论