0

I have an image that move on my cavas at a set speed on the X axis. When I try to rotate it his trejectory changes and he no longer move only on the x axis but also on the Y axis. How can I rotate the image and not change its course?

Bar
  • 19
  • 3
  • 1
    Please look at https://stackoverflow.com/help/minimal-reproducible-example and put enough code into your question so we can see the problem (without having to code it from scratch ourselves). – A Haworth May 28 '22 at 21:01
  • See this answer https://stackoverflow.com/a/43155027/3877726 to rotate image – Blindman67 May 31 '22 at 16:08

1 Answers1

0

If you control the center of rotation, and perform the calculations according to the book (e.g. use Polar coordinates along the way), it should be fine.

Here is an example of a rotating rectangle that moves with its center of mass along a horizontal line:

class Polygon {
    constructor(points) {
        this.points = points;
        this.center = [0, 0]; // center of rotation & positioning
        this.rotation = 0;
        this.polar = points.map(([x, y]) => [Math.sqrt(x*x + y*y), Math.atan2(y, x)]);
    }
    refresh(ctx) {
        let [x0, y0] = this.center;
        this.points = this.polar.map(([dist, angle]) => {
            angle += this.rotation;
            return [Math.cos(angle) * dist + x0,
                    Math.sin(angle) * dist + y0];
        });
        ctx.beginPath();
        ctx.moveTo(...this.points[0]);
        for (let point of this.points) ctx.lineTo(...point);
        ctx.closePath();
        ctx.stroke();
    }
}

let shape = new Polygon([[-20, -10], [20, -10], [20, 10], [-20, 10]]);
shape.center = [20, 50];
let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
requestAnimationFrame(function loop() { 
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    shape.center[0] = (shape.center[0] + 1) % 700;
    shape.rotation += 0.02;
    shape.refresh(ctx);
    requestAnimationFrame(loop);
});
body { margin: 0; padding: 0 }
<canvas width="600" height="170"></canvas>
trincot
  • 317,000
  • 35
  • 244
  • 286