js數學 atan2 cos sin

這裏寫圖片描述

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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章