javascript - 如何让一个对象绕着html5 Canvas 中的一个点转动

标签 javascript canvas html5-canvas coordinates

问题如下图所示 the problem of defining angles

换句话说,如何精确计算每一帧的x和y坐标?

ctx.arc(x,y,radius,0,pi*2,false)

因为在增加一个坐标后,我遇到了如何计算另一个坐标的问题

我试过了,但没用

var step=2,x=100,y=100,r=50,coordinates=[[x,y-r]];
for(var i=1;i <r;i+=step){
bx=x;
x+=step;
y=y-Math.sqrt(Math.pow(r,2)-Math.pow(bx-x,2))
coordinates[i]=[x,y];
}

如果有 jsfiddle 将不胜感激。

最佳答案

var canvas = document.querySelector("#c");
var ctx = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var speed = 10; // Lower is faster


function animate(t){
    ctx.save();
    ctx.clearRect (0 , 0 ,canvas.width ,canvas.height );
    ctx.translate(canvas.width/2, canvas.height/2);
    
    // First circle
    ctx.beginPath();
    ctx.arc(0, 0, 5, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'blue';
    ctx.fill();
    ctx.closePath();
    
    // rotate + move along
    ctx.rotate((t/speed)/100);
    ctx.translate(100,0);
    
    // Orbiting cirle
    ctx.beginPath();
    ctx.arc(0, 0, 10, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'red';
    ctx.fill();
    ctx.closePath();
    
    ctx.restore();
    requestAnimationFrame(animate);
}

requestAnimationFrame(animate);
canvas {
    border: 1px solid black;
}
<canvas id="c" width="512" height="512"></canvas>

关于javascript - 如何让一个对象绕着html5 Canvas 中的一个点转动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26885157/

相关文章:

javascript - 根据它们之间的距离绘制 4 个点?

javascript - Internet Explorer 中的 javascript 无法显示图像

javascript - jQuery 将 div 加载到另一个没有 .html() 方法的地方

javascript - 在递归 setTimeout 函数中使用 sleep

javascript - 通过 Jquery 将图像添加到 Canvas

javascript - 是否可以仅使用 Javascript 将 HTML Canvas 另存为图像?

javascript - 使用 Mocha 测试 Promise

javascript - HTML5 中的多个动态 Canvas

html - 在纯 css 3d 中创建圆柱形状

canvas.toDataURL() 用于大 Canvas