Always use local coordinates to define shapes.
When rendering content intended for conversion, the content should be in its own (local) coordinate system. Think about the image. the top left pixel is always at 0.0 in the image no matter where you render it. Pixels are in their local coordinates, during visualization they move to the canvas (world) coordinates through the current transformation.
So, if you make your shape with the coordinates set to its local point, making the pivot point in its local source (0,0), the display coordinates are saved separately as world coordinates
var shape = { top: -30, // local coordinates with rotation origin left: -60, // at 0,0 width: 120, height: 60, world : { x : canvas.width / 2, y : canvas.height / 2, rot : Math.PI / 12, // 15deg clockwise } };
Now you donβt have to bother translating back and forth ... blah blah is a complete pain.
Just
ctx.save(); ctx.translate(shape.world.x,shape.world.y); ctx.rotate(shape.world.rot); ctx.fillRect(shape.left, shape.top, shape.width, shape.height) ctx.restore();
or event faster and eliminating the need to use save and restore
ctx.setTransform(1,0,0,1,shape.world.x,shape.world.y); ctx.rotate(shape.world.rot); ctx.fillRect(shape.left, shape.top, shape.width, shape.height);
The local origin (0,0) is where the transformation places the translation.
This greatly simplifies the work that needs to be done.
var canvas = document.getElementById('canvas'); canvas.width = 300; canvas.height= 150; var ctx = canvas.getContext('2d'); ctx.fillStyle = "black"; ctx.strokeStyle = "red"; ctx.lineWidth = 2; var shape = { top: -30,
body { font-family : Arial,"Helvetica Neue",Helvetica,sans-serif; font-size : 12px; color : #242729;} canvas { border: 1px solid red; }
<canvas id="canvas"></canvas> <p>Click to grow "and rotate" (I add that to illustrate the local origin)</p> <p>I have added a red box and a line above the box, showing how using the local coordinates to define a shape makes it a lot easier to then manipulate that shape when rendering "see code comments".</p>