0

For some reason, if you set the canvas aspect ratio to 2:1, everything appears normal; any other aspect ratio will make it stretch.

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();

What is the problem here and/or what is the better way to do this?

https://jsfiddle.net/1gx7bv3m/

skara9
  • 4,042
  • 1
  • 6
  • 21

1 Answers1

0

My experience not a good idea to mix styles with canvas...

We can set the aspect ratio directly on the canvas like this:

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>

You can see that I also remove a lot of the calculations you had and I hope that I accomplish the same result you are looking for, a lot less code and much more readable.

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
  • "I hope that I accomplish the same result you are looking for" you are only by luck because they used a small enough rectangle that gets cleared by the circle your clearRect is actually drawing. Just change `w` and `h` to be the size of the canvas and you'll see how your code is actually broken. – Kaiido Nov 29 '21 at 07:38