Skip to content

Instantly share code, notes, and snippets.

@hashrock
Last active January 31, 2024 13:22
Show Gist options
  • Select an option

  • Save hashrock/0e8f10d9a233127c5e33b09ca6883ff4 to your computer and use it in GitHub Desktop.

Select an option

Save hashrock/0e8f10d9a233127c5e33b09ca6883ff4 to your computer and use it in GitHub Desktop.

Revisions

  1. hashrock revised this gist Feb 5, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion svg-drag.js
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@ const Circle = () => {
    x: 100,
    y: 100,
    active: false,
    coords: { x: 0, y: 0 }
    offset: { }
    });

    const handlePointerDown = e => {
  2. hashrock created this gist Feb 5, 2019.
    76 changes: 76 additions & 0 deletions svg-drag.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    import React from "react";
    import ReactDOM from "react-dom";

    const Circle = () => {
    const [position, setPosition] = React.useState({
    x: 100,
    y: 100,
    active: false,
    coords: { x: 0, y: 0 }
    });

    const handlePointerDown = e => {
    const el = e.target;
    const bbox = e.target.getBoundingClientRect();
    const x = e.clientX - bbox.left;
    const y = e.clientY - bbox.top;
    el.setPointerCapture(e.pointerId);
    setPosition({
    ...position,
    active: true,
    offset: {
    x,
    y
    }
    });
    };
    const handlePointerMove = e => {
    const bbox = e.target.getBoundingClientRect();
    const x = e.clientX - bbox.left;
    const y = e.clientY - bbox.top;
    if (position.active) {
    setPosition({
    ...position,
    x: position.x - (position.offset.x - x),
    y: position.y - (position.offset.y - y)
    });
    }
    };
    const handlePointerUp = e => {
    setPosition({
    ...position,
    active: false
    });
    };

    return (
    <circle
    cx={position.x}
    cy={position.y}
    r={50}
    onPointerDown={handlePointerDown}
    onPointerUp={handlePointerUp}
    onPointerMove={handlePointerMove}
    fill={position.active ? "blue" : "black"}
    />
    );
    };

    function App() {
    return (
    <svg viewBox="0 0 400 400" width="400" height="400">
    <Circle />
    </svg>
    );
    }

    const Application = () => {
    return (
    <div>
    <h1>Drag Me</h1>
    <App />
    </div>
    );
    };

    ReactDOM.render(<Application />, document.getElementById("app"));