效果演示:
思路:核心->抛物线公式
1 let a = -((y2-y3)*x1 - (x2-x3)*y1 + x2*y3 - x3*y2) / ((x2-x3) * (x1-x2) * (x1-x3)); 2 let b = ((y2-y3)*x1*x1 + x2*x2*y3 - x3*x3*y2 - (x2*x2 - x3*x3)*y1) / ((x2-x3)*(x1-x2)*(x1-x3)); 3 let c = ((x2*y3 - x3*y2)*x1*x1 - (x2*x2*y3 - x3*x3*y2)*x1 + (x2*x2*x3 - x2*x3*x3)*y1) / ((x2-x3)*(x1-x2)*(x1-x3));
(x1,y1)----起点坐标 (x2,y2) ----终点坐标 (x3,y3)----最高点坐标
上面的公式主要是来求飞行物top值的,公式 ----top = a*x1*x1+b*x1+c
好了我们来看下完整的代码
1 .tian{ 2 width: 100px; 3 height: 30px; 4 background-color: orange; 5 line-height: 30px; 6 text-align: center; 7 position: absolute; 8 left:300px; 9 bottom: 40px; 10 cursor: pointer; 11 } 12 .car{ 13 width: 40px; 14 height: 40px; 15 background-color: #9D2933; 16 position: fixed; 17 text-align: center; 18 line-height: 40px; 19 color:white; 20 right:40px; 21 top:200px; 22 } 23 .fly{ 24 width: 20px; 25 height: 20px; 26 position: absolute; 27 background-color: #FF0000; 28 }
1 <div class="tian">添加到购物车</div> 2 <div class="car">0</div>
1 class Pao{ 2 constructor(obj) { 3 this.tian = this.$(obj[0]) 4 this.car = this.$(obj[1]) 5 this.init() 6 } 7 $(k){ //获取元素方法 8 return document.querySelector(k) 9 } 10 init(){ 11 let num = 0 12 this.tian.onclick = e =>{ 13 let x1 = this.tian.offsetLeft 14 let y1 = this.tian.offsetTop 15 let x2 = this.car.offsetLeft 16 let y2 = this.car.offsetTop 17 let x3 = this.car.offsetLeft - 600 18 let y3 = this.car.offsetTop + 100 19 let a = -((y2-y3)*x1 - (x2-x3)*y1 + x2*y3 - x3*y2) / ((x2-x3) * (x1-x2) * (x1-x3)); 20 let b = ((y2-y3)*x1*x1 + x2*x2*y3 - x3*x3*y2 - (x2*x2 - x3*x3)*y1) / ((x2-x3)*(x1-x2)*(x1-x3)); 21 let c = ((x2*y3 - x3*y2)*x1*x1 - (x2*x2*y3 - x3*x3*y2)*x1 + (x2*x2*x3 - x2*x3*x3)*y1) / ((x2-x3)*(x1-x2)*(x1-x3)); 22 let fly = document.createElement('div') 23 fly.className = 'fly' 24 fly.style.left = x1 + 'px' 25 fly.style.top = y1 + 'px' 26 document.body.appendChild(fly) 27 let left = x1 28 let top = y1 29 let tim = setInterval(()=>{ 30 if(left > x2){ 31 num++ 32 clearInterval(tim) 33 fly.remove() 34 this.car.innerText = num 35 } 36 left+=10 37 top = a*left*left+b*left+c 38 fly.style.left = left + 'px' 39 fly.style.top = top + 'px' 40 41 },1000/60) 42 } 43 } 44 } 45 new Pao(['.tian','.car'])