您的位置:首页 > Web前端 > JavaScript

js数学 atan2 cos sin

2015-07-07 21:15 621 查看


1.给出相对坐标中心o,p1到o的距离l,p1到x轴的角度angle(0~2PI)

left:x0+Math.cos(angle)
top:  y0+Math.sin(angle)


2.给出相对坐标中心o,p1坐标,求p1关于x轴的夹角

//angle大于-Math.PI,小于Math.PI
// (-∏,∏)
var angle=astan2(y1-y0,x1-x0);


案例:



用canvas写一个摆动角在60度到120度之间的循环动画,要求长方体随着摆动跟着转动。

/*
知识点:
摆线转过的角度等于长方体自身旋转的角度
已知angle,求x,y
*/

var canvas,contxt;
canvas=document.getElementById('myCanvas');
contxt=canvas.getContext("2d");

var drawWall=function(){
contxt.save();
contxt.strokeStyle="#000";
contxt.lineWidth=5;
contxt.beginPath();
contxt.moveTo(100,0);
contxt.lineTo(500,0)
contxt.stroke();
contxt.closePath();
contxt.restore();
};
var drawLine=function(x,y){
contxt.save();
contxt.strokeStyle="#000";
contxt.lineWidth=2;
contxt.beginPath();
contxt.moveTo(300,0);
contxt.lineTo(300+x,y)
contxt.stroke();
contxt.closePath();
contxt.restore();
};
var drawRect=function(x,y,angle){
contxt.save();
contxt.fillStyle="#f00";
contxt.translate(300+x,y);
contxt.rotate(angle+Math.PI/2);
contxt.rect(-100,-50,200,100);
contxt.fill();
contxt.restore();

};

var angle,increase,width,height,x,y,radius;
angle=Math.PI/3;
increase=Math.PI/3/200;
width=200;
height=100;
radius=300;

var onframe=function(){
contxt.clearRect(0,0,800,600);
drawWall();
x=radius*Math.cos(angle);
y=radius*Math.sin(angle);
drawLine(x,y);
drawRect(x,y,angle);

if(angle>(Math.PI/3*2)){
increase=-increase;
}else if(angle<Math.PI/3){
increase=-increase;
}
angle+=increase;
window.requestAnimationFrame(onframe);
};
onframe();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: