gsap(一) 跟着鼠標移動的小球

gsap.quickTo()

<div style="width: 500px;height: 400px;background-color: lavender;margin-left:40px;margin-top:30px;" #parent>

  <div style="width: 30px;height: 30px;border-radius: 50%;background-color: lightpink;" #child></div>

</div>
  const parent = this.parent.nativeElement;
    const child = this.child.nativeElement;
    let xTo = gsap.quickTo(child, 'x', {duration: .4, ease: 'power3'});
    let yTo = gsap.quickTo(child, 'y', {duration: .4, ease: 'power3'});
    // 從固定值到x 200的動畫
    // xTo(200)
    // 從500->100 的動畫
    // xTo(100, 500)
    const offsetX: number = parent.getBoundingClientRect().x
    const offsetY: number = parent.getBoundingClientRect().y
    const width: number = parent.getBoundingClientRect().width;
    const height: number = parent.getBoundingClientRect().height;
    const childWidth: number = child.getBoundingClientRect().width;
    const childHeight: number = child.getBoundingClientRect().height;
    parent.addEventListener('mousemove', (e: MouseEvent) => {
      let x = e.pageX - offsetX - childWidth / 2;
      let y = e.pageY - offsetY - childHeight / 2;
      let leftBound = width - childWidth;
      let bottomBound = height - childHeight;
      console.log(childWidth, bottomBound);
      if (x <= 0) {
        x = 0;
      } else if (x > leftBound) {
        x = leftBound
      }
      if (y <= 0) {
        y = 0;
      } else if (y > bottomBound) {
        y = bottomBound
      }
      xTo(x);
      yTo(y)
    })

gsap.quickSetter()

只需要把對應的改改

   let xTo = gsap.quickTo(child, 'x', {duration: .4, ease: 'power3'});
    let yTo = gsap.quickTo(child, 'y', {duration: .4, ease: 'power3'});
     xSet(x)
      ySet(y)

設置隨機位置

var boxSet = gsap.quickSetter("#box", "css");
boxSet({x:"+=100", y:"random(-100, 100)"});

設置圓的位置

var circleSet = gsap 。quickSetter ( "#circle" , "attr" ); 
circleSet ({ cx : "+=100" , cy : "random(-100, 100)" });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章