Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Javascript - rotating canvas causes stretching

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/

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!