Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ 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

Auto Save

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="root">
  <div class="graphic"></div>
  <div class="actions">
    <p>Drag shapes!</p>
    <div>
      <h3>Generate</h3>
      <button class="add-circle">Circle</button>
      <button class="add-square">Square</button>
      <button class="add-triangle">Triangle</button>
    </div>
    <div>
      <h3>Edit</h3>
      <button class="remove">Remove selected shape</button>
    </div>
    <div>
      <button class="undo">Undo</button>
      <button class="redo">Redo</button>
    </div>
  </div>
</div>
              
            
!

CSS

              
                html,
body {
  padding: 0;
  margin: 0;
}

.root {
  display: flex;
  padding: 10px;
}

.graphic {
  width: 320px;
  margin-right: 10px;
  border-radius: 2px;
  font-size: 0;
  flex: 0 auto;
}

.graphic svg {
  border: 1px solid #000;
  border-radius: 2px;
  background: #fafafa;
  overflow: hidden;
}

.actions {
  font-size: 0;
  flex: 1;
}

.actions p {
  font-size: 12px;
  margin: 4px 0 0;
  padding: 0;
  color: #a7a7a7;
}

.actions h3 {
  margin: 10px 0;
  font-size: 14px;
}

.actions > div {
  margin-top: 4px;
}

.actions > div:first-child {
  margin-top: 0;
}

.actions button {
  margin-right: 4px;
}

@media (max-width: 420px) {
  .root {
    display: block;
    padding: 0;
  }
  
  .graphic {
    width: 100%;
  }
  
  .graphic svg {
    border-top: none;
    border-left: none;
    border-right: none;
    border-radius: 0;
  }
  
  .actions {
    padding: 0 10px 10px 10px;
  }

  .actions h3 {
    margin: 8px 0 5px;
  }
}
              
            
!

JS

              
                import { bind, wire } from 'https://dev.jspm.io/hyperhtml/esm';
import serializr from 'https://dev.jspm.io/serializr';

////////////////////////////////////////////////////////////
////////////////////////// Models //////////////////////////
////////////////////////////////////////////////////////////

const { createModelSchema, serialize, deserialize, primitive, list } = serializr;
const ShapeType = { Circle: 0, Square: 1, Triangle: 2 };

class Shape {
  constructor(data = { }) {
    const {
      posX = 40,
      posY = 40,
      fill = `#${Math.floor(Math.random() * 16777215).toString(16)}`,
      selected = false
    } = data;
    this.shapeType = undefined;
    this.posX = posX;
    this.posY = posY;
    this.tempX = undefined;
    this.tempY = undefined;
    this.fill = fill;
    this.selected = selected;
  }

  isTouch(posX, posY) {
    return (
      posX > this.posX && 
      posY > this.posY && 
      posX < (this.posX + 20) && 
      posY < (this.posY + 20)
    );
  }

  travel(posX, posY) {
    this.tempX = posX;
    this.tempY = posY;
  }

  arrive() {
    if (this.tempX !== undefined) {
      this.posX = this.tempX;
      this.posY = this.tempY;
      this.tempX = undefined;
      this.tempY = undefined;      
    }
  }
}

Shape.shapeType = undefined;

createModelSchema(Shape, {
  shapeType: primitive(),
  posX: primitive(),
  posY: primitive(),
  fill: primitive(),
  selected: primitive(),
});

class Circle extends Shape {
  constructor(data = { }) {
    super(data);
    const {
      cx = 10,
      cy = 10,
      r = 10
    } = data;
    this.shapeType = ShapeType.Circle;
    this.cx = cx;
    this.cy = cy;
    this.r = r;
  }
}

Circle.shapeType = ShapeType.Circle;

createModelSchema(Circle, {
  cx: primitive(),
  cy: primitive(),
  r: primitive(),
});

class Square extends Shape {
  constructor(data = { }) {
    super(data);
    const { 
      x = 0,
      y = 0,
      width = 20,
      height = 20
    } = data;
    this.shapeType = ShapeType.Square;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }
}

Square.shapeType = ShapeType.Square;

createModelSchema(Square, {
  x: primitive(),
  y: primitive(),
  width: primitive(),
  height: primitive(),
});

class Triangle extends Shape {
  constructor(data = { }) {
    super(data);
    const { 
      points = [[10, 0], [0, 20], [20, 20]]
    } = data;
    this.shapeType = ShapeType.Triangle;
    this.points = points;
  }
}

Triangle.shapeType = ShapeType.Triangle;

createModelSchema(Triangle, {
  points: list(list(primitive())),
});

function getShapeClass(shapeType) {
  return [ Circle, Square, Triangle ].find(C => C.shapeType === shapeType);
}

class Shapes {
  constructor() {
    this._listeners = [];
    this._shapes = [];
  }

  getAll() {
    return this._shapes.concat();
  }

  getSelected() {
    return this._shapes.find(s => s.selected);
  }

  getByPosition(posX, posY) {
    return this.getAll()
      .reverse()
      .find(s => s.isTouch(posX, posY));
  }

  selectOne(shape) {
    this._shapes.forEach(s => s.selected = false);
    shape.selected = true;
    this.emit();
  }

  add(shape) {
    this._shapes.push(shape);
    this.emit();
  }

  remove(shape) {
    this._shapes = this._shapes.filter(s => s !== shape);
    this.emit();
  }

  travel(shape, posX, posY) {
    shape.travel(posX, posY);
    this.emit();
  }

  arrive(shape) {
    shape.arrive();
    this.emit();
  }

  on(callback) {
    this._listeners.push(callback);
  }

  emit() {
    this._listeners.forEach(l => l());
  }

  snapshot() {
    return serialize(this._shapes);
  }

  restore(snapshot) {
    this._shapes = snapshot.map(d => deserialize(getShapeClass(d.shapeType), d));
    this.emit();
  }
}

////////////////////////////////////////////////////////////
////////////////////////// Moment //////////////////////////
////////////////////////////////////////////////////////////

class History {
  constructor(shapes) {
    this._undoStack = [];
    this._redoStack = [];
    this._shapes = shapes;
  }

  take() {
    const snapshot = this._shapes.snapshot();
    this._undoStack.push(snapshot);
    this._redoStack = [];
  }

  undo() {
    if (this._undoStack.length > 0) {
      const dump = this._undoStack.pop();
      const snapshot = this._shapes.snapshot();
      this._redoStack.push(snapshot);
      this._shapes.restore(dump);
    }
  }

  redo() {
    if (this._redoStack.length > 0) {
      const dump = this._redoStack.pop();
      const snapshot = this._shapes.snapshot();
      this._undoStack.push(snapshot);
      this._shapes.restore(dump);
    }
  }
}

////////////////////////////////////////////////////////////
/////////////////////// Presentation ///////////////////////
////////////////////////////////////////////////////////////

const docEl = document.documentElement;
const graphic = document.querySelector('.graphic');
const render = bind(graphic);
const shapes = new Shapes();
const history = new History(shapes);

function update() {
  render`
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
      <g stroke-width=".5">
        ${shapes.getAll().map((shape) => {
          const x = shape.tempX === undefined ? shape.posX : shape.tempX;
          const y = shape.tempY === undefined ? shape.posY : shape.tempY;
          const stroke = shape.selected ? 'yellow' : 'none';
          if (shape instanceof Circle) {
            return wire(shape, 'svg')`
              <g transform="${`translate(${x} ${y})`}" stroke="${stroke}">
                <circle cx=${shape.cx} cy=${shape.cy} r=${shape.r} fill=${shape.fill}></circle>
              </g>
            `;
          } else if(shape instanceof  Square) {
            return wire(shape, 'svg')`
              <g transform="${`translate(${x} ${y})`}" stroke="${stroke}">
                <rect x=${shape.x} y=${shape.y} width=${shape.width} height=${shape.height} fill=${shape.fill}></rect>
              </g>
            `;
          } else {
            return wire(shape, 'svg')`
              <g transform="${`translate(${x} ${y})`}" stroke="${stroke}">
                <polygon points=${shape.points.join(' ')} fill=${shape.fill}></polygon>
              </g>
            `;
          }
        })}
      </g>
    </svg>
  `;
}

update();
shapes.on(update);

////////////////////////////////////////////////////////////
////////////////////// Event Handler ///////////////////////
////////////////////////////////////////////////////////////

const addCircle = document.querySelector('.add-circle');
const addSquare = document.querySelector('.add-square');
const addTriangle = document.querySelector('.add-triangle');
const remove = document.querySelector('.remove');
const undo = document.querySelector('.undo');
const redo = document.querySelector('.redo');

addCircle.addEventListener('click', create.bind(null, Circle));
addSquare.addEventListener('click', create.bind(null, Square));
addTriangle.addEventListener('click', create.bind(null, Triangle));

remove.addEventListener('click', () => {
  const shape = shapes.getSelected();
  if (shape) {
    history.take();
    shapes.remove(shape);
  }
});

undo.addEventListener('click', () => history.undo());
redo.addEventListener('click', () => history.redo());

function random(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function create(Shape) {
  history.take();
  const shape = new Shape({ 
    posX: random(0, 80), 
    posY: random(0, 80) 
  });
  shapes.add(shape);
  shapes.selectOne(shape);
}

let dragging = false;
let shape = undefined;
let ratio = 0;
let startX = 0;
let startY = 0;

function handlePointerStart(event) {
  if (event.target.closest('.graphic')) {
    ratio = parseFloat(window.getComputedStyle(graphic).width) / 100;
    startX = event.offsetX;
    startY = event.offsetY;
    if (event.touches) {
      const { pageX, pageY } = event.touches[0];
      const { left, top } = graphic.getBoundingClientRect();
      startX = pageX - left;
      startY = pageY - top;
    }
    shape = shapes.getByPosition(startX / ratio, startY / ratio);
    if (shape) {
      dragging = true;
      shapes.selectOne(shape);
    }
  }
}

function handlePointerMove(event) {
  if (dragging && shape && event.target.closest('.graphic')) {
    event.preventDefault();
    let { offsetX, offsetY } = event;
    if (event.touches) {
      const { pageX, pageY } = event.touches[0];
      const { left, top } = graphic.getBoundingClientRect();
      offsetX = pageX - left;
      offsetY = pageY - top;
    }
    const movedX = shape.posX + (offsetX - startX) / ratio;
    const movedY = shape.posY + (offsetY - startY) / ratio;
    shapes.travel(shape, movedX, movedY);
  }
}

function handlePointerEnd() {
  if (dragging && shape) {
    if (shape.tempX !== undefined) {
      history.take();      
    }
    shapes.arrive(shape);
    dragging = false;
    shape = undefined;
  }
}

if ('ontouchstart' in document.documentElement) {
  docEl.addEventListener('touchstart', handlePointerStart);
  docEl.addEventListener('touchmove', handlePointerMove);
  docEl.addEventListener('touchend', handlePointerEnd);
} else {
  docEl.addEventListener('mousedown', handlePointerStart);
  docEl.addEventListener('mousemove', handlePointerMove);
  docEl.addEventListener('mouseup', handlePointerEnd);
}

              
            
!
999px

Console