I need to draw rotated image data on canvas. (This is an gwt project and context is instance of com.google.gwt.canvas.dom.client.Context2d)
I trying to use following code for that:
context.rotate(rotation);
context.putImageData(data, x, y);
context.rotate(-rotation);
but it draw not rotated image. If I change code like this
context.rotate(rotation);
context.fillRect(x, y, 100, 50);
context.rotate(-rotation);
than rotated rectangle will be drawn on canvas. Is it a API bug, or my falt? What can I do to correct it?
Edited I try to use drawImage() with some other image instead putImageDate() to test how it works. It works with rotation fine. But I need to draw ImageData than I take form other canvas. Is it any fast methods to translate ImageData to ImageElement? In what units ImageData returns its size?
The rotate() method allows you to rotate a drawing object on the canvas. The rotate() method accepts a rotation angle in radians. If the angle is positive, the rotation is clockwise. In case the angle is negative, the rotation is counterclockwise.
To do that you need to first context. translate to the rect's centerpoint before rotating. // move the rotation point to the center of the rect ctx. translate( x+width/2, y+height/2 ); // rotate the rect ctx.
To rotate a shape around its own center, you must first translate the canvas to the center of the shape, then rotate the canvas, then translate the canvas back to 0,0, and then draw the shape. This example first translates (moves) the center of the canvas to the center of the square (cx, cy).
putImageData
is not affected by the transformation matrix.
This is by the Spec's orders:
The current path, transformation matrix, shadow attributes, global alpha, the clipping region, and global composition operator must not affect the getImageData() and putImageData() methods.
What you can do is putImageData
to an in-memory canvas, and then
context.rotate(rotation);
context.drawImage(inMemoryCanvas, x, y)
context.rotate(-rotation);
onto your regular canvas.
NOTE: from your edit you seem to imply that you might just be drawing from one canvas to another without changing any of the imagedata. If this is the case, definitely just use drawImage(othercanvas, x, y)
instead of using getImageData
and putImageData
if possible. Using drawImage
is far faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With