0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【interact.js】ドラッグアンドドロップテスト

Posted at

いつか何かに使えるであろうドラッグアンドドロップのテスト

import React, { useEffect, useRef } from "react";
import interact from "interactjs";

const DraggableSquare = () => {
  const squareRef = useRef(null);

  useEffect(() => {
    //MEMO: squareRef.currentが!(false)のとき、処理を終了する
    if (!squareRef.current) {
      return;
    }

    interact(squareRef.current).draggable({
      inertia: true,
      modifiers: [
        interact.modifiers.restrictRect({
          restriction: "parent",
          endOnly: true,
        }),
      ],
      autoScroll: true,
      onmove: dragMoveListener,
    });
  }, []);

  const dragMoveListener = (event) => {
    var target = event.target,
      x = (parseFloat(target.getAttribute("data-x")) || 0) + event.dx,
      y = (parseFloat(target.getAttribute("data-y")) || 0) + event.dy;

    target.style.transform = "translate(" + x + "px, " + y + "px)";

    target.setAttribute("data-x", x);
    target.setAttribute("data-y", y);
  };

  return <div ref={squareRef} style={{ width: 100, height: 100, backgroundColor: "blue" }} />;
};

export default DraggableSquare;

実行すると、マウス位置とのズレが発生するので今後改善するかも

ほな、また

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?