How to translate and rotate a bitmap on canvas?

by giovanny.lueilwitz , in category: Javascript , 3 months ago

How to translate and rotate a bitmap on canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 3 months ago

@giovanny.lueilwitz 

To translate and rotate a bitmap on a canvas, you can use the following steps:

  1. Translate: To move the bitmap to a different position on the canvas, you can use the canvas.translate(x, y) method, where x and y are the coordinates of the new position you want to move the bitmap to.


For example:

1
canvas.translate(100, 100); // move the bitmap 100 pixels to the right and 100 pixels down


  1. Rotate: To rotate the bitmap on the canvas, you can use the canvas.rotate(degrees, px, py) method, where degrees is the angle of rotation in degrees and px and py are the coordinates of the point around which to rotate the bitmap.


For example:

1
canvas.rotate(45, bitmap.getWidth() / 2, bitmap.getHeight() / 2); // rotate the bitmap by 45 degrees around its center


Putting it all together, you can translate and rotate a bitmap on a canvas as follows:

1
2
3
canvas.translate(100, 100); // move the bitmap
canvas.rotate(45, bitmap.getWidth() / 2, bitmap.getHeight() / 2); // rotate the bitmap
canvas.drawBitmap(bitmap, 0, 0, null); // draw the bitmap on the canvas


This will translate the bitmap 100 pixels to the right and 100 pixels down, and then rotate it by 45 degrees around its center before drawing it on the canvas.