简体   繁体   中英

rotating an image without changing its projectory in canvas

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?

If you control the center of rotation, and perform the calculations according to the book (eg 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM