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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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="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>
</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: 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;
  }
  
  .actions p {
    margin-top: 4px;
  }

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

JS

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

class Shape {
  constructor(data = { }) {
    const {
      posX = 40,
      posY = 40,
      fill = `#${Math.floor(Math.random() * 16777215).toString(16)}`,
      selected = false
    } = data;
    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;      
    }
  }
}

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

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

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

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());
  }
}

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

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

const docEl = document.documentElement;
const graphic = document.querySelector('.graphic');
const render = bind(graphic);
const shapes = new 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) {
    shapes.remove(shape);
  }
});

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

function create(Shape) {
  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) {
    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