如何在gsap中将对象移动到屏幕上的某个点

问题描述 投票:0回答:1

我有一个具有特定类名的 dom 元素,我试图在用户完成拖动后将该元素移动到屏幕中的特定点。

为了做到这一点,我的计划是在我想要将点移动到的位置创建一个临时 dom 元素,移动原始元素,然后删除临时元素。

这是我的代码

gsap.registerPlugin(Draggable, MotionPathPlugin)
const selector = ".my-obj";
Draggable.create(selector, {
    type: "x,y",
    onDragEnd: function (e: any) {
        const pointTag = document.createElement("temp-point-tag");
        pointTag.style.position = 'absolute';
        pointTag.style.top = 200 + window.scrollY + "px";
        pointTag.style.left = 400 + window.scrollX + "px";
        pointTag.style.width = "3px"
        pointTag.style.height = "3px"
        pointTag.style.backgroundColor = "red"
        document.body.appendChild(pointTag);

        const point = MotionPathPlugin.convertCoordinates(pointTag, document.querySelector(selector), { x: 0, y: 0 })
        gsap.to(selector, { x: point.x, y: point.y });
    },
});

我的代码没有按预期工作。它没有静态行为。如果我拖动物体。它会进入屏幕中的随机位置,也可能会超出屏幕。

据我从文档中了解到,

MotionPathPlugin.convertCoordinates
的预期行为是相对于我指定的对象坐标移动到 {x:0, y:x}。

为什么

MotionPathPlugin.convertCoordinates
不起作用?将对象移动到屏幕中特定点(x,y)的正确方法是什么?

示例代码笔:我正在尝试在拖动事件结束后将红色方块移动到红点https://codepen.io/abozanona/pen/wvZMdLd

javascript gsap
1个回答
0
投票

gsap.registerPlugin(Draggable);
const selector = ".my-obj";
Draggable.create(selector, {
  type: "x,y",
  onDragEnd: function (e) {
    const pointTag = document.createElement("temp-point-tag");
    pointTag.style.position = "absolute";
    pointTag.style.top = "100px";
    pointTag.style.left = "100px";
    pointTag.style.width = "3px";
    pointTag.style.height = "3px";
    pointTag.style.backgroundColor = "red";
    document.body.appendChild(pointTag);

    const point = pointTag.getBoundingClientRect();
    console.log(point);
    gsap.to(selector, { left: point.left, top: point.top, x: 0, y: 0 });
  }
});
.my-obj {
  width: 50px;
  height: 50px;
  position: absolute;
  bottom: 50px;
  left: 50%;
  background-color: red;
  will-change: transform;
}
<div class="my-obj"></div>

<script src="https://unpkg.com/gsap@3/dist/Draggable.min.js"></script>

<script src="https://unpkg.com/gsap@3/dist/CSSRulePlugin.min.js"></script>
<script src="https://unpkg.co/gsap@3/dist/gsap.min.js"></script>

解决方案如下。我猜你不需要使用额外的插件来更改位置值。 这是解决方案的 codepen 链接。 链接

© www.soinside.com 2019 - 2024. All rights reserved.