Por alguna razón, si establece la relación de aspecto del lienzo en 2:1, todo parece normal; cualquier otra relación de aspecto hará que se estire.
const canvas = document.getElementById('canvas'); canvas.style.width = '400px'; canvas.style.height = '400px'; canvas.style.border = '2px solid black'; const ctx = canvas.getContext('2d'); const w = canvas.width/4; const h = canvas.height/4; var relativeAngle = 0; //(Target is the position I want it; in this case, right in the middle) const targetX = canvas.width/2; const targetY = canvas.height/2; const targetDist = Math.sqrt(targetX ** 2 + targetY ** 2); const targetAngle = Math.atan(targetY / targetX) * 180 / Math.PI; ctx.fillStyle = 'red' function draw(){ relativeAngle += 3; let targetRelativeAngle = targetAngle - relativeAngle; let targetRelativeX = targetDist * Math.cos(targetRelativeAngle * Math.PI / 180); let targetRelativeY = targetDist * Math.sin(targetRelativeAngle * Math.PI / 180); ctx.clearRect(0,0,canvas.width,canvas.height); ctx.save(); ctx.rotate(relativeAngle * Math.PI / 180); ctx.translate(targetRelativeX,targetRelativeY); ctx.fillRect(-w/2,-h/2,w,h); ctx.restore(); window.requestAnimationFrame(draw); } draw();¿Cuál es el problema aquí y/o cuál es la mejor manera de hacer esto?
Mi experiencia no es buena idea mezclar estilos con lienzo...
Podemos establecer la relación de aspecto directamente en el lienzo de esta manera:
const canvas = document.getElementById('canvas'); canvas.width = canvas.height = 400 const ctx = canvas.getContext('2d'); const w = canvas.width / 4; const h = canvas.height / 4; ctx.fillStyle = 'red' function refresh() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.translate(w, h) ctx.rotate(0.02); ctx.fillRect(-w / 2, -h / 2, w, h); ctx.translate(-w, -h) window.requestAnimationFrame(refresh); } refresh(); <canvas id="canvas"></canvas>Puede ver que también eliminé muchos de los cálculos que tenía y espero lograr el mismo resultado que está buscando, mucho menos código y mucho más legible.