首页 > 解决方案 > How to give the illusion of rotation to a moving ball

问题描述

 //draw method
 draw() {
     //draw the ball
     ctx.beginPath();
     ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI), false;
     ctx.moveTo(this.xPos, this.yPos);
     var i;
     //use a for loop 
     for (i = 1; i < 8; i++) {
         var x = this.radius * Math.cos(i * 2 / 7 * Math.PI) + this.xPos;
         var y = this.radius * Math.sin(i * 2 / 7 * Math.PI) + this.yPos;
         ctx.lineTo(x, y);
         ctx.moveTo(this.xPos, this.yPos);
     }

     ctx.lineTo(this.xPos, this.yPos);
     ctx.fillStyle = "rgba(125, 125, 125, 1)";
     ctx.strokeStyle = "red";
     ctx.fill();
     ctx.stroke();
 }

I'm completely new to graphics programming, and I am wondering how I could use a rotate method to shift all the lines in the circle (created by the draw method) by a fixed amount of radians as it moves

here is an image of the output:

output

标签: javascripthtmlgraphics

解决方案


有更有效的方法来解决这个问题,但它们需要 webgl 或 webgpu 之类的东西,这样才能得到你想要的东西:

这是二维旋转矩阵: 在此处输入图像描述

在你的 draw 方法中添加一个theta参数,并在 draw 参数之外在循环的每次迭代中将其增加一个小量,例如 0.001(记住在绘制之前清除你的画布)。

然后在你的方法里面,计算C你的圆心。围绕其质心C'旋转任何形状的公式是:

R(theta) * (S - C) + C

其中 S 是形状中所有点的集合,R(theta) 是在 theta 处评估的旋转矩阵。

换句话说,对于车轮中的每一对 (x, y) 坐标,首先减去中心,然后将得到的向量 <x, y> 乘以左旋转矩阵 (R * V),最后vector <x', y'> 表示旋转后的形状。


推荐阅读