- You need to translate the canvas to the center point at which you will do the rotation
- Rotate based on the angle you have
- Draw image
- Reset transformation
In code it would be these lines:
ctx.translate(player.x, player.y); // translate to center of rotation
ctx.rotate(angle + 0.5*Math.PI); // rotate, here +90deg to comp image dir.
ctx.translate(-player.x, -player.y); // translate back
ctx.drawImage(ships.blueBeginers,player.x-15,player.y-15); // draw image
ctx.setTransform(1,0,0,1,0,0); // reset transforms (identity matrix)
The flickering is because you calculate the atan2 angle each frame. When position equals click position you will have atan of a very small value toggling due to the adding of cos/sin later.
You can fix this by caching the angle on your click object as in this version:
However, you need a conditional check to stop animating as now you just add the values from cos/sin and nothing is stopping it (here is one way of doing it).
Tip 1: Create the image of the ship facing right. This would correspond to 0° and save you from adding 90° each time.
Tip 2: Cache the angle value and calculation once then you don't have to calculate atan2/cos/sin each time as they are relative expensive operation.