Solved: How to rotate with GWTCanvas

Having trouble rotating something you’ve drawn with GWTCanvas?

It took me a little while to work out, but GWTCanvas works slightly differently to Graphic2D in Java. It’s important to realise that with GWTCanvas, when you invoke “rotate(r)” you’re actually transforming the coordinate space that will be used for subsequent drawing.

canvas.moveTo(50, 50);
canvas.lineTo(50, 10);

canvas.stroke();

Produces:

In order to rotate it, you must invoke rotate before you start any drawing.
canvas.translate(50, 50);
canvas.rotate(Math.toRadians(45));
canvas.translate(-50, -50);

canvas.moveTo(50, 50);
canvas.lineTo(50, 10);

canvas.stroke();

Tadaa!

The same is also true for other transformation methods such as “scale” and “translate”.

2 thoughts on “Solved: How to rotate with GWTCanvas”

  1. Perhaps you could wrap GWTCanvas and offer an interface that’s more in keeping with Graphic2D? (assuming that’s the more well-known standard)

    Either way, it would be nice to have a rotate(Coordinate centerPoint, Angle rotation) method to wrap up the translate-rotate-translate chain.

Leave a Reply

Your email address will not be published. Required fields are marked *