javascript - 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:
解决方案
有更有效的方法来解决这个问题,但它们需要 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'> 表示旋转后的形状。
推荐阅读
- javascript - 如何在 javascript 中翻译 Go des 代码
- gremlin - 在 Gremlin 中创建从一个遍历到另一个遍历的边
- reactjs - Jest 参数化测试 - 如果条件在里面
- azure-cosmosdb - 用于配置备份配置的 ARM 模板
- ios - wkWebview 跨界 swift IOS
- python - 无法在 PYTHONPATH 中设置路径
- python - 为什么每当我尝试执行 F 字符串时我的代码都不起作用
- python - 在 python/pandas 中连接文本和数字
- c - 使用宏的 C 枚举
- c++ - 需要在 C++ 程序中询问汽车制造商