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

javascript_抛物线系列_04已知起点和终点画抛物线

2018-01-24 14:23 453 查看

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{
margin:0;
padding:0;
list-style: none
}
#box{
position:absolute;
left:0px;
top:0px;
width:100px;
height:100px;
background-color:pink;
}

</style>
</head>
<body style="height:1000px">

</body>
</html>
<script type="text/javascript">

//要画抛物线:
//已知条件:
//1、已知起点和终点
//2、根据起点和终点进行计算p

let startPoint={x:200,y:400};
let endPoint = {x:500,y:10};
let p=0;
//初始化数据(计算p)
function initData(){
let tempPoint = {x:endPoint.x-startPoint.x,y:endPoint.y-startPoint.y};
//y2 = -2px;
p = (tempPoint.y*tempPoint.y)/(2*tempPoint.x);
}

//初始化界面
function initUI(){
//外观(打点):
drawPoint(startPoint);

drawPoint(endPoint);
}

//打点函数(在界面上指定的位置画一个点)
function drawPoint(point){
let  divObj = document.createElement("div");
let cssStr = "position:absolute;width:10px;height:10px;background-color:red;";
cssStr += "left:"+point.x+"px;top:"+point.y+"px;";
divObj.style.cssText = cssStr;
document.body.appendChild(divObj);
}

let myTimer=null;
function moveObj(){
if(myTimer!=null){
window.clearInterval(myTimer);
}
myTimer = setInterval(goStep,10);
}

let x = 0;
let incX = 1;//x的方向

function goStep(){
//1、假定起点在原点的抛物线
x=x+incX;
if(x>endPoint.x-startPoint.x){
window.clearInterval(myTimer);
myTimer = null;
return;
}
y = -1*Math.sqrt(2*p*x);

//2、改变抛物线的原点(移动原点,偏移)。
let xTemp = x+startPoint.x;
let yTemp = y+startPoint.y;

//外观(打点):
drawPoint({x:xTemp,y:yTemp});
}

window.onload = function(){
initData();//计算p
initUI();//在界面上画出起点和终点。
moveObj();//根据起点和终点绘制抛物线

}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  抛物线