使用React实现小球动画

通过点击按钮 在该位置创建一个小球,然后通过transition和贝塞尔曲线控制小球的抛物线  

return (
    <div>
      
      <button onClick={(e)=>{handleClick(e)}} 
        style={{position:'absolute',top:50,left:500,
        borderRadius:'50%',border:'none',color:'white',
        backgroundColor:'lightblue',
        width:25,
        height:25,
        lineHeight:1,
        fontSize:16,
        textAlign:'center'}}>+</button>
     
    
        <button onClick={(e)=>{handleClick(e)}} 
        style={{
        position:'absolute',
        top:100,left:500,
        borderRadius:'50%',border:'none',color:'white',
        backgroundColor:'lightblue',
        width:25,
        height:25,
        lineHeight:1,
        fontSize:16,
        textAlign:'center'}}>+</button>
      
      
      <div ref={cart} style={{position:'absolute',left:200,top:500}}>
        <img src={Cart} alt="" style={{width:50,height:50}} />
      </div>

    </div>
  )

点击按钮传入事件对象  将clientX、clientY值传给创建小球的函数 

const cart=useRef(null)

  const handleClick=e=>{
    const {clientX,clientY}=e
    createBall(clientX,clientY)
  }
  const createBall=(left,top)=>{
    const ball=document.createElement('div')
    ball.style.position='absolute'
    ball.style.top=top-10+'px'
    ball.style.left=left-10+'px'
    ball.style.width='10px'
    ball.style.height='10px'
    ball.style.backgroundColor='red'
    ball.style.borderRadius='50%'
   
    ball.style.transition = 'left .6s linear,top .6s cubic-bezier(0.5,-0.5,1,1)';
    //x1:在y1为负数情况下,值越大x轴抛出距离越远;取值在0-1之间,否则小球会直接显示在购物车上
    //y1:为负值时,值越大,x轴向上抛出距离越远,为正数时,值越大,小球会越紧贴y轴,距离越向下)
    //x2:取值在0-1之间,值越大,按钮到购物车之间形成的s形曲线越不明显,取值为1时,形成平滑半U形曲线
    //y2:值大于1时:小球会越沿着y轴向下运动再进入购物车
    
    document.body.appendChild(ball) 
    requestAnimationFrame(()=>{
      ball.style.left=cart.current.offsetLeft+cart.current.offsetWidth/2 + 'px'
      ball.style.top=cart.current.offsetTop+'px'
    })
    ball.ontransitionend=function(){
      ball.remove()
    }

贝塞尔曲线css用法接收四个参数 cubic-bezier(x1,y1,x2,y2) x1 和 x2 必须是 0 到 1 之间的数字。关于cubic-bezier(0.5,-0.5,1,1)参数设置并不是固定的 这样形成的抛物线是比较平滑的 符合应用场景  参数解释只是我的理解 更多信息请参考w3schoolcubic-beziericon-default.png?t=N7T8https://www.w3school.com.cn/cssref/func_cubic-bezier.asp以下是 x1=0.5  时的抛物线效果 

0.5效果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值