css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              @import "bourbon";

$highlighted-color: rgba(red, .5);
$selected-color: red;

@include keyframes(pulse) {
  100% { @include transform(scale(0.975))}
}

ul {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

strong {
  margin: 0 5px 0 0;
}

.app {
  display: flex;
  width: 1024px;
  margin: 0 auto;
}

.viewport {
  position: relative;
  flex: 0 0 500px;
  overflow: hidden;
  width: 500px;
  height: 500px;
  margin: 0 10px 0 0;
  background: silver;
}

.sprite {
  position: absolute;

  &::after {
    @include animation(pulse .5s ease-in alternate infinite);
    border: dashed 1px rgba(white, .5);
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    pointer-events: none;
  }
  
  &.is-highlighted::after {
    border: dashed 2px $highlighted-color;
  }

  &.is-selected::after {
    border: solid 2px $selected-color;
  }
}

.sprite-editor {
  flex-grow: 1;
}

.sprite-data {
  display: flex;
  width: 100%;
  padding: 2px;
  cursor: default;
  white-space: nowrap;
  
  &.is-highlighted {
    background: $highlighted-color;
  }

  &.is-selected {
    background: $selected-color;
  }
  
  button {
    cursor: pointer;
  }
}

.sprite-width,
.sprite-x,
.sprite-y {
  width: 50px;
}

.samples li {
  display: flex;
}

.samples input {
  flex-grow: 1;
}

.reorder-downward {
  margin: 0 5px 0 0;
}
            
          
!
            
              // adapted from https://bitbucket.org/snippets/jdubray/9dgKp/sam-sample

// http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript#answer-2117523
const uuid = () => `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g, c => {
  const r = Math.random()*16|0
  const v = c === `x` ? r : (r&0x3|0x8)
  return v.toString(16);
})

// MODEL

const model = {
  sprites: [{
    id: uuid(),
    name: `Background`,
    x: -45, y: -17, width: 1000,
    image: `https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-background.jpg`,
  }, {
    id: uuid(),
    name: `Clouds #1`,
    x: 125, y: 294, width: 275,
    image: `https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-cloud.png`,
  }, {
    id: uuid(),
    name: `Character`,
    x: 195, y: 259, width: 125,
    image: `https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-knight.png`,
  }, {
    id: uuid(),
    name: `Clouds #2`,
    x: 272, y: 137, width: 275,
    image: `https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-cloud.png`,
  }, {
    id: uuid(),
    name: `Clouds #3`,
    x: 42, y: 217, width: 250,
    image: `https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-cloud.png`,
  }]
}

model.present = data => {
  const sprites = model.sprites
  
  if (`editSprite` in data) {
    const sprite = sprites.find(s => s.id === data.id)
    if (`image` in data) {
      sprite.image = data.image
    }
    if (`x` in data) {
      sprite.x = data.x
    }
    if (`y` in data) {
      sprite.y = data.y
    }
    if (`width` in data) {
      sprite.width = data.width
    }
  }
  
  if (`addSprite` in data) {
    const trimmedName = (data.addSprite.name || ``).trim()
    if (trimmedName.length > 0) {
      data.addSprite.name = trimmedName
      sprites.push(data.addSprite)
    }
  }
  
  if (`deleteSprite` in data) {
    model.sprites = sprites.filter(sprite => sprite.id !== data.deleteSprite.id)
  }
  
  if (`reorderUpward` in data) {
    let at = sprites.findIndex(sprite => sprite.id === data.reorderUpward.id)
    if (at > 0 && at < sprites.length) {
      [sprites[at - 1], sprites[at]] = [sprites[at], sprites[at - 1]]
    }
  }
  
  if (`reorderDownward` in data) {
    let at = sprites.findIndex(sprite => sprite.id === data.reorderDownward.id)
    if (at >= 0 && at < sprites.length - 1) {
      [sprites[at + 1], sprites[at]] = [sprites[at], sprites[at + 1]]
    }
  }

  const dehighlightAll = () => sprites.forEach(sprite => sprite.isHighlighted = false)

  if (`highlightSprite` in data) {
    dehighlightAll()
    let which = sprites.findIndex(sprite => sprite.id === data.highlightSprite)
    if (which !== -1) {
      sprites[which].isHighlighted = true 
    }
  }
  
  if (`dehighlightAll` in data) {
    dehighlightAll()
  }

  const deselectAll = () => sprites.forEach(sprite => sprite.isSelected = false)

  if (`selectSprite` in data) {
    deselectAll()
    let which = sprites.findIndex(sprite => sprite.id === data.selectSprite)
    if (which !== -1) {
      sprites[which].isSelected = true 
    }
  }
  
  if (`deselectAll` in data) {
    deselectAll()
  }
  
  if (`beginDraggingSprite` in data) {
    const sprite = sprites.find(sprite => sprite.id === data.beginDraggingSprite.id)
    if (sprite) {
      model.isDraggingSprite = sprite
      model.dragInfo = {
        documentStartingPosition: {
          x: data.beginDraggingSprite.x,
          y: data.beginDraggingSprite.y,
        },
        spriteStartingPosition: {
          x: sprite.x,
          y: sprite.y,
        }
      }
    }
  }

  if (`dragSprite` in data) {
    if (model.isDraggingSprite) {
      model.isDraggingSprite.x = model.dragInfo.spriteStartingPosition.x + (data.dragSprite.x - model.dragInfo.documentStartingPosition.x)
      model.isDraggingSprite.y = model.dragInfo.spriteStartingPosition.y + (data.dragSprite.y - model.dragInfo.documentStartingPosition.y)
    }
  }

  if (`endDraggingSprite` in data) {
    delete model.isDraggingSprite
  }

  state.render(model)

  // render blasts the whole dom, so reset previous text cursor
  textCursor.restore()
}

// VIEW

const view = {}

view.spriteInput = (sprite, field) => {
  const inputId = `sprite-${field}-${sprite.id}`
  return `
  <input
    type="text"
    class="sprite-${field}"
    value="${sprite[field]}"
    oninput="
      textCursor.save('${inputId}')
      actions.editSprite({id: '${sprite.id}', ${field}: this.value})
    "
    data-input-id="${inputId}"
  >`
}

view.spriteAttributesEditor = sprite => {
  const classList = [`sprite-data`]
  if (sprite.isHighlighted) {
    classList.push(`is-highlighted`)
  }
  if (sprite.isSelected) {
    classList.push(`is-selected`)
  }
  
  return `
  <li class="${classList.join(` `)}" data-id="${sprite.id}">
    <button
      class="reorder-upward"
      onclick="actions.reorderUpward({id: '${sprite.id}'})"
    >↑</button>
    <button
      class="reorder-downward"
      onclick="actions.reorderDownward({id: '${sprite.id}'})"
    >↓</button>
    <strong>${sprite.name}&nbsp;</strong>
    ${view.spriteInput(sprite, `image`)}
    Width:${view.spriteInput(sprite, `width`)}
    X:${view.spriteInput(sprite, `x`)}
    Y:${view.spriteInput(sprite, `y`)}
    <button onclick="actions.deleteSprite({id: '${sprite.id}'})">✗</button>
  </li>`
}

const toPx = v => !Number.isNaN(v) ? `${v}px` : v

view.sprite = s => {
  let classList = [`sprite`]
  if (s.isHighlighted) {
    classList.push(`is-highlighted`)
  }
  if (s.isSelected) {
    classList.push(`is-selected`)
  }

  return `
    <div
      data-id="${s.id}"
      class="${classList.join(` `)}"
      style="
        top: ${toPx(s.y)};
        left: ${toPx(s.x)};
      "
    >
      <img
        src="${s.image}"
        width="${s.width}"
      >
    </div>
  `
}

view.main = model => `
  <div class="app">
    <div class="viewport">
      ${model.sprites.map(sprite => view.sprite(sprite)).join(``)}
    </div>
    <div class="sprite-editor">
      <h1>Scene Editor</h1>
      <p>Draws sprites in the order they are listed, using the given attributes.</p>
      <p>Hover/click sprites to select. Drag to move. Up/down arrows to reorder selection.</p>
      <ul class="sprite-list">
        ${model.sprites.map(sprite => view.spriteAttributesEditor(sprite)).join(``)}
      </ul>
      Name: <input type="text">
      <button
        class="add-sprite"
        onclick="actions.addSprite({name: this.previousElementSibling.value})"
      >Add Sprite</button>
      <p>Try adding/pasting these above:</p>
      <ul class="samples">
        <li><strong>Castle</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-background.jpg"></li>
        <li><strong>Knight</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-knight.png"></li>
        <li><strong>Clouds</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-cloud.png"></li>
        <li><strong>Jungle</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-background-jungle.jpg"></li>
        <li><strong>Monkey</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-monkey.png"></li>
        <li><strong>Bushes</strong><input type="text" value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/207435/sam-bushes.png"></li>
      </ul>
    </div>
  </div>
`

view.display = html => {
  document.body.innerHTML = html
}

// STATE

const state = {}

state.representation = model => {
  view.display(view.main(model))
}

state.nextAction = model => {
  // TODO
}

state.render = model => {
  state.representation(model)
  state.nextAction(model)
}

// ACTIONS

const actions = {}

actions.editSprite = (data, present=model.present) => {
  data.editSprite = data.id
  data.sprite = {
    x: data.x,
    y: data.y,
    width: data.width,
    image: data.image,
  }
  present(data)
}

actions.addSprite = (data, present=model.present) => {
  data.id = uuid()
  data.x = 0
  data.y = 0
  data.width = ``
  data.image = ``
  present({addSprite: data})
}

actions.deleteSprite = (data, present=model.present) => {
  present({deleteSprite: data})
}

actions.reorderUpward = (data, present=model.present) => {
  present({reorderUpward: data})
}

actions.reorderDownward = (data, present=model.present) => {
  present({reorderDownward: data})
}

actions.highlightSprite = (data, present=model.present) => {
  present({highlightSprite: data})
}

actions.dehighlightAll = (data, present=model.present) => {
  present({dehighlightAll: data})
}

actions.selectSprite = (data, present=model.present) => {
  present({selectSprite: data})
}

actions.deslectAll = (data, present=model.present) => {
  present({deslectAll: data})
}

actions.beginDraggingSprite = (data, present=model.present) => {
  present({beginDraggingSprite: data})  
}

actions.dragSprite = (data, present=model.present) => {
  present({dragSprite: data})
}

actions.endDraggingSprite = (data, present=model.present) => {
  present({endDraggingSprite: data})
}

// TEXT CURSOR

const textCursor = {
  inputId: 0,
  carePosition: 0,
}

textCursor.getInputById = id => {
  return document.querySelector(`[data-input-id="${id}"]`)
}

textCursor.save = inputId => {
  textCursor.inputId = inputId
  textCursor.caretPosition = textCursor.getInputById(inputId).selectionStart
}

textCursor.restore = () => {
  const element = textCursor.getInputById(textCursor.inputId)
  if (element) {
    element.focus()
    let caretPosition = textCursor.caretPosition
    if (caretPosition > element.value.length) {
      caretPosition = element.value.length
    }
    element.setSelectionRange(caretPosition, caretPosition)
  }
}

// view.init() seems silly for a single file, so:
state.render(model)

// tricky: click/mousedown won't work
$(document).on(`mouseup`, `.sprite-data input`, event => {
  const inputId = $(event.currentTarget).attr(`data-input-id`)
  textCursor.save(inputId)
})

const spriteById = id => {
  return model.sprites.find(sprite => sprite.id === id)
}

// SPRITE DRAGGING

$(document.body).on(`mousedown`, `.sprite`, event => {
  event.preventDefault()

  const id = event.currentTarget.getAttribute(`data-id`)
  const sprite = spriteById(id)
  if (!sprite) {
    return
  }

  actions.selectSprite(id)
  actions.beginDraggingSprite({
    id,
    x: event.clientX,
    y: event.clientY,
  })
})

$(document.body).on(`mousemove`, `.viewport`, event => {
  event.preventDefault()

  if (model.isDraggingSprite) {
    actions.dragSprite({
      x: event.clientX,
      y: event.clientY,
    })
  }
})

$(document.body).on(`mouseup`, `.viewport`, event => {
  event.preventDefault()
  
  if (model.isDraggingSprite) {
    actions.endDraggingSprite()
  }
})

// HIGHLIGHTING & SELECTING SPRITES

$(document.body).on(`mouseenter`, `.sprite, .sprite-data`, event => {
  const id = event.currentTarget.getAttribute(`data-id`)
  const sprite = spriteById(id)
  if (!sprite || sprite.isHighlighted) {
    return
  }
  actions.highlightSprite(id)
})

$(document.body).on(`click`, `.sprite-data`, event => {
  const id = event.currentTarget.getAttribute(`data-id`)
  const sprite = spriteById(id)
  if (!sprite || sprite.isSelected) {
    return
  }
  actions.selectSprite(id)
})

$(document.body).on(`mouseleave`, `.viewport`, event => {
  actions.dehighlightAll({})
})

const selectedSprite = () => {
  return model.sprites.find(sprite => sprite.isSelected)
}

$(document).on(`keydown`, event => {
  switch (event.keyCode) {
    case 38: { // up arrow
      event.preventDefault()
      const sprite = selectedSprite()
      if (sprite) {
        actions.reorderUpward({id: sprite.id})
      }
    } break
    case 40: { // down arrow
      event.preventDefault()
      const sprite = selectedSprite()
      if (sprite) {
        actions.reorderDownward({id: sprite.id})
      }
    } break
  }
})

/*
Original images pulled from:
castle -> https://s-media-cache-ak0.pinimg.com/originals/88/99/59/8899591fcde45ec3991ef48efb053e74.jpg
jungle -> http://img15.deviantart.net/834c/i/2015/140/6/2/game_background_concept_sketch_by_dearcane-d8u1yc4.jpg
knight -> https://s3.amazonaws.com/gameartpartnersimagehost/wp-content/uploads/2016/06/Chibi-Knight-4-Royalty-Free-Game-Art.png
monkey -> https://upload.wikimedia.org/wikipedia/en/e/e1/Donkey_kong.png
clouds -> http://pngimg.com/upload/cloud_PNG32.png
bushes -> https://s-media-cache-ak0.pinimg.com/originals/ed/67/06/ed6706a63d3a93e98355dfed764593b9.png
*/

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console