原生js实现点击添加购物车按钮出现飞行物飞向购物车

时间:2022-02-14 09:48:13

效果演示:

原生js实现点击添加购物车按钮出现飞行物飞向购物车

思路:核心->抛物线公式

 let a = -((y2-y3)*x1 - (x2-x3)*y1 + x2*y3 - x3*y2) / ((x2-x3) * (x1-x2) * (x1-x3));
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

好了我们来看下完整的代码

 .tian{
width: 100px;
height: 30px;
background-color: orange;
line-height: 30px;
text-align: center;
position: absolute;
left:300px;
bottom: 40px;
cursor: pointer;
}
.car{
width: 40px;
height: 40px;
background-color: #9D2933;
position: fixed;
text-align: center;
line-height: 40px;
color:white;
right:40px;
top:200px;
}
.fly{
width: 20px;
height: 20px;
position: absolute;
background-color: #FF0000;
}

css代码

 <div class="tian">添加到购物车</div>
<div class="car">0</div>

html代码

 class Pao{
constructor(obj) {
this.tian = this.$(obj[0])
this.car = this.$(obj[1])
this.init()
}
$(k){ //获取元素方法
return document.querySelector(k)
}
init(){
let num = 0
this.tian.onclick = e =>{
let x1 = this.tian.offsetLeft
let y1 = this.tian.offsetTop
let x2 = this.car.offsetLeft
let y2 = this.car.offsetTop
let x3 = this.car.offsetLeft - 600
let y3 = this.car.offsetTop + 100
let a = -((y2-y3)*x1 - (x2-x3)*y1 + x2*y3 - x3*y2) / ((x2-x3) * (x1-x2) * (x1-x3));
let b = ((y2-y3)*x1*x1 + x2*x2*y3 - x3*x3*y2 - (x2*x2 - x3*x3)*y1) / ((x2-x3)*(x1-x2)*(x1-x3));
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));
let fly = document.createElement('div')
fly.className = 'fly'
fly.style.left = x1 + 'px'
fly.style.top = y1 + 'px'
document.body.appendChild(fly)
let left = x1
let top = y1
let tim = setInterval(()=>{
if(left > x2){
num++
clearInterval(tim)
fly.remove()
this.car.innerText = num
}
left+=10
top = a*left*left+b*left+c
fly.style.left = left + 'px'
fly.style.top = top + 'px' },1000/60)
}
}
}
new Pao(['.tian','.car'])

js代码