Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="canvas">
  <svg class="canvas__svg" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice"></svg>
  <div class="canvas__controls">
    <button class="canvas__btn canvas__btn--fill canvas__btn--active">
      <svg class="canvas__btn-icon">
        <path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"></path>
      </svg>
    </button>
    <button class="canvas__btn canvas__btn--delete">
      <svg viewBox="0 0 24 24" class="canvas__btn-icon">
        <polyline points="3 6 5 6 21 6"></polyline>
        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
        <line x1="10" y1="11" x2="10" y2="17"></line>
        <line x1="14" y1="11" x2="14" y2="17"></line>
      </svg>
    </button>
  </div>
</div>
              
            
!

CSS

              
                * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

body {
  height: 100vh;
  display: grid;
  place-items: center;
  color: #1f2933;
  background: hsl(0, 0%, 100%);
}

.canvas {
  position: relative;
  /* max-width: 32rem;
  aspect-ratio: 1/1; */
  width: 100vw;
  height: 100vh;
}

.canvas__svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
}

.canvas__svg-bg {
}

.canvas__controls {
  position: absolute;
  bottom: 1.5rem;
  left: 50%;
  display: flex;
  transform: translateX(-50%);
  z-index: 2;
}

.canvas__btn {
  width: 2.75rem;
  height: 2.75rem;
  margin-right: 1rem;
  border: none;
  cursor: pointer;
  background: none;
}

.canvas__btn:last-of-type {
  margin-right: 0;
}

.canvas__btn-icon {
  width: 24px;
  height: 24px;
  fill: none;
  stroke-width: 1.5;
  stroke: currentColor;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.canvas__shape {
  fill: none;
  stroke: currentColor;
  stroke-width: 3;
}

.canvas__dummy-shape {
  fill: none;
  stroke: #7b8794;
  stroke-dasharray: 4;
  stroke-width: 2;
  vector-effect: non-scaling-stroke;
  pointer-events: none;
}

.canvas__point {
  stroke: #000;
  stroke-width: 3;
  fill: #fff;
  /*   vector-effect: non-scaling-stroke; */
}

.closed .canvas__point[data-index="0"] {
  fill: #fff;
}

.canvas__btn--active {
  color: #1f2933;
}

              
            
!

JS

              
                import { gsap } from "https://cdn.skypack.dev/gsap";
import { Draggable } from "https://cdn.skypack.dev/gsap/Draggable";
import { SVG } from "https://cdn.skypack.dev/@svgdotjs/svg.js";
import { v4 as uuidv4 } from "https://cdn.skypack.dev/uuid";
import { spline } from "https://cdn.skypack.dev/@georgedoescode/spline";

console.clear();

const pop = document.createElement("audio");
pop.src =
  "https://assets.codepen.io/5367578/navigation_forward-selection-minimal.wav";

const create = document.createElement("audio");
create.src = "https://assets.codepen.io/5367578/ui_unlock.wav";

const btnClickSound = document.createElement("audio");
btnClickSound.src = "https://assets.codepen.io/5367578/ui_lock.wav";

// GSAP
gsap.registerPlugin(Draggable);

gsap.registerEffect({
  name: "elasticIn",
  effect: (targets, config) => gsap.to(targets, { ...config }),
  defaults: {
    scale: 1,
    transformOrigin: "50%",
    duration: 1.5,
    ease: "elastic.out(1, 0.3)"
  }
});

gsap.registerEffect({
  name: "scaleOut",
  effect: (targets, config) => gsap.to(targets, { ...config }),
  defaults: {
    scale: 0,
    transformOrigin: "50%",
    duration: 0.25,
    overwrite: true
  }
});

// Create canvas instance
const canvas = {
  svg: SVG(".canvas__svg"),
  cursorMode: "DRAW",
  buttons: {
    copy: document.querySelector(".canvas__btn--copy"),
    delete: document.querySelector(".canvas__btn--delete"),
    fill: document.querySelector(".canvas__btn--fill")
  },
  currentShape: null,
  shapes: []
};

canvas.shapes.push(createShape());
canvas.currentShape = canvas.shapes[0];

// Event listeners
canvas.buttons.delete.addEventListener("click", () => {
  btnClickSound.play();

  gsap.to(canvas.currentShape.group.node, {
    opacity: 0,
    onComplete: () => {
      canvas.currentShape.group.remove();
      canvas.shapes.push(createShape());
      canvas.currentShape = canvas.shapes[canvas.shapes.length - 1];
    }
  });
});

canvas.buttons.fill.addEventListener("click", (e) => {
  e.stopPropagation();
  btnClickSound.play();

  if (canvas.currentShape.isClosed) {
    gsap.set(canvas.currentShape.pathEl.node, {
      fill: `hsl(${Math.random() * 260}, 100%, 80%)`
    });
  }
});

canvas.svg.node.addEventListener("click", (e) => {
  if (e.target.classList.contains("canvas__svg")) {
    if (canvas.currentShape.isClosed) {
      gsap.effects.scaleOut(".canvas__point");
      canvas.shapes.push(createShape());
      canvas.currentShape = canvas.shapes[canvas.shapes.length - 1];
    }

    addPointToShape(e);
    setShapePathOpen();
    renderShapePath();
  }

  if (e.target.classList.contains("canvas__point")) {
    if (e.target.getAttribute("data-index") === "0") {
      closeShape();
    }
  }
});

window.addEventListener("mousemove", (event) => {
  const { x, y } = getRelativeCoords(event);

  const points = [
    ...canvas.currentShape.points,
    {
      x: x - canvas.currentShape.draggableGroup.x,
      y: y - canvas.currentShape.draggableGroup.y
    }
  ];

  gsap.set(canvas.currentShape.dummyPath.node, {
    attr: {
      d: spline(points, 1, false)
    }
  });
});

function closeShape() {
  create.play();
  setShapePathClosed();
  renderShapePath();

  canvas.currentShape.isClosed = true;
  canvas.currentShape.pathEl.attr("class", "canvas__shape");
  canvas.currentShape.group.attr("class", "closed");

  gsap.set(canvas.currentShape.dummyPath, {
    opacity: 0
  });

  gsap.fromTo(
    [
      canvas.currentShape.pathEl.node,
      canvas.currentShape.group.node.querySelectorAll(".canvas__point")
    ],

    {
      scale: 0.75,
      transformOrigin: "50%"
    },
    {
      scale: 1,
      transformOrigin: "50%",
      duration: 1,
      ease: "elastic.out(1, 0.3)"
    }
  );

  gsap.fromTo(
    canvas.currentShape.pathEl.node,
    {
      fill: "hsl(140, 0%, 100%)"
    },
    {
      duration: 0.5,
      fill: canvas.currentShape.fill
    }
  );
}

function createShape() {
  const id = uuidv4();
  const shapeGroup = canvas.svg.group().attr("id", id);

  const draggableGroup = Draggable.create(shapeGroup.node, {
    onClick(e) {
      gsap.set(canvas.currentShape.dummyPath, {
        opacity: 0
      });

      const id = e.target.parentNode.getAttribute("id");
      canvas.currentShape = canvas.shapes.find((s) => s.id === id);

      if (canvas.currentShape.isClosed) {
        gsap.effects.scaleOut(".canvas__point");
        gsap.effects.elasticIn(
          canvas.currentShape.group.node.querySelectorAll(".canvas__point")
        );
      }
    }
  });

  return {
    id,
    points: [],
    dummyPath: shapeGroup.path().attr("class", "canvas__dummy-shape"),
    pathEl: shapeGroup.path().attr("class", "canvas__shape"),
    pathData: "",
    isClosed: false,
    group: shapeGroup,
    draggableGroup: draggableGroup[0],
    fill: `hsl(${Math.random() * 260}, 100%, 80%)`
  };
}

function setShapePathOpen() {
  canvas.currentShape.pathData = spline(canvas.currentShape.points, 1, false);
}

function setShapePathClosed() {
  canvas.currentShape.pathData = spline(canvas.currentShape.points, 1, true);
}

function renderShapePath(dur = 1) {
  const path = canvas.currentShape.pathEl.node;

  gsap.set(path, {
    attr: {
      d: canvas.currentShape.pathData
    }
  });

  const l = path.getTotalLength();

  gsap.set(path, { strokeDasharray: l });

  gsap.fromTo(
    path,
    { strokeDashoffset: l / canvas.currentShape.points.length - 1 },
    { strokeDashoffset: 0, duration: dur, ease: "expo.out" }
  );
}

function createPoint(x, y) {
  const id = uuidv4();

  const el = canvas.currentShape.group
    .circle(24)
    .cx(x)
    .cy(y)
    .attr("data-index", canvas.currentShape.points.length)
    .attr("data-point-id", id)
    .attr("class", "canvas__point")
    .scale(0);

  el.node.addEventListener("mouseenter", () => {
    gsap.to(el.node, {
      duration: 0.25,
      fill: "#000"
    });
  });

  el.node.addEventListener("mouseleave", () => {
    gsap.to(el.node, {
      duration: 0.25,
      fill: "#fff"
    });
  });

  gsap.effects.elasticIn(el.node);

  Draggable.create(el.node, {
    onPress: function (e) {
      e.stopPropagation();
    },
    onDrag(e) {
      const { x, y } = getRelativeCoords(e);

      const point = canvas.currentShape.points.find((p) => p.id === id);

      point.x = x - canvas.currentShape.draggableGroup.x;
      point.y = y - canvas.currentShape.draggableGroup.y;

      if (canvas.currentShape.isClosed) {
        setShapePathClosed(canvas.currentShape);
      } else {
        setShapePathOpen(canvas.currentShape);
      }

      renderShapePath(0);
    }
  });

  return { id, x, y, el };
}

function addPointToShape(event) {
  pop.currentTime = 0;
  pop.play();

  const { x, y } = getRelativeCoords(event);

  canvas.currentShape.points.push(
    createPoint(
      x - canvas.currentShape.draggableGroup.x,
      y - canvas.currentShape.draggableGroup.y
    )
  );
}

const pt = canvas.svg.node.createSVGPoint();

function getRelativeCoords(evt) {
  pt.x = evt.clientX;
  pt.y = evt.clientY;

  const cursorpt = pt.matrixTransform(canvas.svg.node.getScreenCTM().inverse());

  return {
    x: cursorpt.x,
    y: cursorpt.y
  };
}

// Animate in UI elements
gsap.fromTo(
  ".canvas",
  {
    opacity: 0,
    y: 50
  },
  {
    opacity: 1,
    y: 0,
    duration: 0.5
  }
);

gsap.fromTo(
  "button",
  {
    opacity: 0,
    y: 50
  },
  {
    opacity: 1,
    y: 0,
    duration: 1.5,
    stagger: 0.1,
    ease: "elastic.out(1, 0.3)"
  }
);

              
            
!
999px

Console