So I am doing a basic Asteroids clone as an intro to HTML5 canvas. I want to be able to rotate the main player while leaving the other objects on screen alone. Currently I am using transform and rotate on the canvas to allow the player to move, which works well.. but since it rotates the entire canvas it affects other shapes on screen. Is the general way to do this, to instead have each shape keep track of its own positions and perform manual transformations on the shape itself while leaving the canvas alone? Can I possibly give my shape a CSS class and control it on its own that way? Should I be using more than 1 canvas so that I can control rotations individually? Not sure what the accepted way is to handle multiple on screen images/shapes all with their own movement and rotation patterns simultaneously. My gut is telling me to have each shape track its own positions and just perform the math on the shape object itself... but then I would not be using the Canvas APIs rotate at all.
My app currently: https://jsfiddle.net/0o2pwLhn/
And a code snippet for the rotation:
// player draw test
function drawShip() {
ctx.beginPath();
ctx.moveTo(shipStartX, shipStartY);
ctx.lineTo(shipStartX + 8, shipStartY + 20);
ctx.lineTo(shipStartX, shipStartY + 15);
ctx.lineTo(shipStartX - 8, shipStartY + 20);
ctx.lineTo(shipStartX, shipStartY);
ctx.translate(shipStartX, shipCenterY);
ctx.rotate((Math.PI / 180) * shipMoveDegree)
ctx.translate(-shipStartX, -shipCenterY);
ctx.stroke();
ctx.closePath();
}
Do the save() and restore() methods on the CanvasRenderingContext2D maybe come into play here? I have tried experimenting with it but havent gotten anywhere. I tried using save() and restore() but the issue is that once I restore, the player just gets set right back to its original spot.. since I am never actually changing its position... just rotating the entire canvas. The similar question here Is it possible to rotate an image on an HTML5 canvas, without rotating the whole canvas? explains how to use save() and rotate() which I think is on the right track.. but does not solve the issue I have because the player location is reset back to the start when the key is lifted, because I set the degrees back to 0 on keyup. How can I maintain the current rotation of a single shape regardless of the rest of the canvas?