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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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 id="view">
  <div id="world">
    <img id="bee" width="150" height="150" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/bee.svg?v=1">   
  </div>
  <div id="scroll-bounds"></div>
</div>

<div id="quick-settings"></div>

              
            
!

CSS

              
                * {
  box-sizing: border-box;
}

html, body {
  height: 100%;
  min-height: 100%;
}

#quick-settings {
  position: fixed;
  top: 10px;
  right: 210px;
  right: 170px;
}

#view {
  position: relative;
  width: 100%;
  height: 100%;  
  overflow: hidden;
}

#world {
  position: absolute; 
  background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/ground-11.jpg?v=1);
  width: 5000px;
  height: 10000px;
}

#bee {
  position: absolute;
  filter: drop-shadow(8px 8px 6px rgba(0,0,0,0.75));
}

#scroll-bounds {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
  border: 4px dotted #fff;
  border: 4px dotted rgba(255,255,255,0.5);
}

              
            
!

JS

              
                console.clear();
const log = console.log.bind(console);

QuickSettings.useExtStyleSheet();

//
// TICKER LISTENER
// =========================================================================== 
class TickerListener {
  
  constructor(public fn, public context, public prev, public next) {
    
    if (prev) {
      prev.next = this;
    }
    
    if (next) { 
      next.prev = this; 
    }
  }
  
  emit(deltaTime) {
    
    if (this.fn) {
      if (this.context) {
        this.fn.call(this.context, deltaTime);
      } else {
        this.fn(deltaTime);
      }
    }
    
    return this.next;
  }
}

//
// TICKER
// =========================================================================== 
class Ticker {
    
  targetFPMS = 0.06;
  maxElapsedMS = 100;
  elapsedMS = 1 / this.targetFPMS;
  lastTime = -1;
  deltaTime = 1;
  speed = 1;
  started = false;
  requestId = null;
  
  head = new TickerListener(null);
  tail = this.head;
  
  get FPS() { return 1000 / this.elapsedMS; }
  
  tick = time => {
    this.requestId = null;
    this.update(time);
    this.requestId = requestAnimationFrame(this.tick);
  };
  
  add(fn, context) {
    
    this.tail = new TickerListener(fn, context, this.tail, null);
    
    if (!this.started) {
      this.start();
    }    
    return this;
  }
  
  start() {
    if (!this.started) {
      this.started = true;
      this.lastTime = performance.now();
      this.requestId = requestAnimationFrame(this.tick);
    }    
  }
   
  update(currentTime = performance.now()) {
    
    let elapsedMS;
    
    if (currentTime > this.lastTime) {
      
      elapsedMS = this.elapsedMS = currentTime - this.lastTime;
      
      if (elapsedMS > this.maxElapsedMS) {
        elapsedMS = this.maxElapsedMS;
      }
      
      this.deltaTime = elapsedMS * this.targetFPMS * this.speed;
      
      let listener = this.head.next;
      
      while (listener) {
        listener = listener.emit(this.deltaTime);
      }
      
    } else {
      this.deltaTime = this.elapsedMS = 0;
    }
    
    this.lastTime = currentTime;
  }
}

//
// KEYBOARD
// =========================================================================== 
enum Key {
  LEFT = 37,
  UP = 38,
  RIGHT = 39,  
  DOWN = 40
}

class Keyboard {
  
  keys = {};
  
  constructor() {
    document.addEventListener("keydown", this.keyHandler);
    document.addEventListener("keyup", this.keyHandler);
  }
    
  keyHandler = event => {
    const keyCode = event.keyCode;
    if (keyCode in this.keys) {
      event.preventDefault();
      this.keys[keyCode] = event.type === "keydown";
    }
  }
  
  isDown(keyCode) {
    return this.keys[keyCode];    
  }
  
  addKeys(keys) {    
    for (let key of keys) {
      this.keys[key] = false;
    }
  } 
}

//
// RECTANGLE
// =========================================================================== 
class Rectangle {
  constructor(x = 0, y = 0, width = 0, height = 0) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    
    this.sizeID = 0;
    this.positionID = 0;
  }
  
  get left() { return this.x; }  
  get top() { return this.y; }
  get right() { return this.x + this.width; }  
  get bottom() { return this.y + this.height; }
    
  get centerX() { return this.x + this.halfWidth; }
  set centerX(value) { this.x = (value - this.halfWidth); }  
  
  get centerY() { return this.y + this.halfHeight; }
  set centerY(value) { this.y = (value - this.halfHeight); }
  
  get x() { return this._x; }  
  set x(value) {
    if (this._x !== value) {
      this._x = value;
      this.positionID++;
    }
  }
  
  get y() { return this._y; }  
  set y(value) {
    if (this._y !== value) {
      this._y = value;
      this.positionID++;
    }
  }
  
  get width() { return this._width; }  
  set width(value) {
    if (this._width !== value) {
      this.halfWidth = (this._width = value) / 2;
      this.sizeID++;
    }
  }
  
  get height() { return this._height; }  
  set height(value) {
    if (this._height !== value) {
      this.halfHeight = (this._height = value) / 2;
      this.sizeID++;
    }
  }
    
  pad(paddingX, paddingY) {
    
    paddingX = paddingX || 0;
    paddingY = paddingY || ((paddingY !== 0) ? paddingX : 0);
    
    this.x -= paddingX;
    this.y -= paddingY;
    
    this.width += paddingX * 2;
    this.height += paddingY * 2;
    
    return this;
  }
  
  centerOn(target) {
    this.x = target.centerX - this.halfWidth;
    this.y = target.centerY - this.halfHeight;
    return this;
  }
  
  copy(rectangle) {
    this.x = rectangle.x;
    this.y = rectangle.y;
    this.width = rectangle.width;
    this.height = rectangle.height;
    return this;
  }
}

//
// ACTOR
// =========================================================================== 
class Actor extends Rectangle {
  
  constructor(element, options) {
    super();
        
    TweenLite.set(element, { x: "+=0", overwrite: false });
    
    this.element = element;
    this.transform = element._gsTransform;
    
    if (options) {
      Object.assign(this, options);
    }
    
    this.x = 0;
    this.y = 0;        
    this.vx = 0;
    this.vy = 0;    
    
    this.originID = 0;            
    
    this.refresh();
  }
    
  get originX() { return this._originX; }  
  set originX(value) {
    if (this._originX !== value) {
      this._originX = value;
      this.originID++;
    }
  }
  
  get originY() { return this._originY; }  
  set originY(value) {
    if (this._originY !== value) {
      this.originID++;
      this._originY = value;
    }
  }       
  
  refresh() {   
    this.width = this.element.offsetWidth || this.element.width || 0;
    this.height = this.element.offsetHeight || this.element.height || 0;
    return this;
  }
  
  render() {
    
    let config;
    
    if (this.resizable && this.sizeID) {
      this.sizeID = 0;
      config = config || {};
      config.width = this.width;
      config.height = this.height;
    }
    
    if (this.positionID) {
      this.positionID = 0;
      config = config || {};
      config.x = this.x;
      config.y = this.y;
    }
    
    if (this.originID) {
      this.originID = 0;
      config = config || {};    
      config.transformOrigin = `${this.originX}px ${this.originY}px`;
    }
    
    if (config) {
      TweenLite.set(this.element, config);
    }
  }
  
  move(xAxis, yAxis, delta) {
           
    this.vx += xAxis * acceleration * delta;
    this.vy += yAxis * acceleration * delta;

    let speed = Math.sqrt(this.vx * this.vx + this.vy * this.vy);
    let angle = Math.atan2(this.vy, this.vx);

    speed = clamp(speed, 0, maxSpeed)

    if (speed > friction) {
      speed -= friction;
    } else {
      speed = 0;
    }

    this.vx = Math.cos(angle) * speed;
    this.vy = Math.sin(angle) * speed;
    
    this.x += this.vx;
    this.y += this.vy;
    
    if (this.bounds) {
            
      if (this.x < 0) {
        this.x = 0;
        this.vx = 0;
      } else if (this.x > this.bounds.width - this.width) {
        this.x = this.bounds.width - this.width;
        this.vx = 0;
      }
      
      if (this.y < 0) {
        this.y = 0;
        this.vy = 0;
      } else if (this.y > this.bounds.height - this.height) {
        this.y = this.bounds.height - this.height;
        this.vy = 0;
      }      
    }
    
    return this;           
  }
}

//
// CAMERA
// =========================================================================== 
class Camera extends Rectangle {
  
  constructor(world, view, options) {
    super();
    
    if (options) {
      Object.assign(this, options);
    }
    
    this.world = world;
    this.view = view;  
    this.scrollBounds = this.scrollBounds || new Rectangle();    
    this.refresh();
  }
  
  refresh() {
    this.setPadding(this.paddingX, this.paddingY);
    return this;
  }
  
  setPadding(paddingX = 0, paddingY = 0) {
        
    this.scrollBounds.copy(this.view);    
    
    this.paddingX = clamp(paddingX, 0, 0.5);
    this.paddingY = clamp(paddingY, 0, 0.5);
    
    const x = -this.view.width  * paddingX;
    const y = -this.view.height * paddingY;
        
    this.scrollBounds.pad(x, y);       
    this.xOffset = this.scrollBounds.width / 2;
    this.yOffset = this.scrollBounds.height / 2; 
    
    return this;
  }
   
  follow(sprite, delta) {
    
    const view = this.view;
    const world = this.world;
    
    var x = this.x;
    var y = this.y;
    
    var lBounds = this.x + view.halfWidth - this.xOffset;
    var rBounds = this.x + view.halfWidth + this.xOffset;
    var tBounds = this.y + view.halfHeight - this.yOffset;
    var bBounds = this.y + view.halfHeight + this.yOffset;
    
    if(sprite.x < lBounds) {
      x = sprite.x - (view.halfWidth - this.xOffset);
    } else if(sprite.right > rBounds) {
      x = sprite.right - (view.halfWidth + this.xOffset);
    }
    
    if(sprite.y < tBounds) {
      y = sprite.y - (view.halfHeight - this.yOffset);
    } else if(sprite.bottom > bBounds) {
      y = sprite.bottom - (view.halfHeight + this.yOffset);
    }
    
    if (this.xOffset * 2 < sprite.width) {
      x = sprite.centerX - this.view.halfWidth;
    }
    
    if (this.yOffset * 2 < sprite.height) {
      y = sprite.centerY - this.view.halfHeight;
    }
    
    this.x = clamp(x, 0, world.width - this.view.width);
    this.y = clamp(y, 0, world.height - this.view.height);
    
    this.world.x = -this.x;
    this.world.y = -this.y;
        
    this.world.originX = sprite.centerX;
    this.world.originY = sprite.centerY;
    
    this.scrollBounds.originX = (sprite.centerX - view.centerX) + (this.scrollBounds.halfWidth - this.x);
    this.scrollBounds.originY = (sprite.centerY - view.centerY) + (this.scrollBounds.halfHeight - this.y);
    
    return this;
  }  
}

//
// APP
// =========================================================================== 
const select = document.querySelector.bind(document);
const ticker = new Ticker();
const keyboard = new Keyboard();

let maxSpeed = 25;
let friction = 0.4;
let acceleration = 1;
let rotation = 0;
let scale = 1;
let paddingX = 0.25;
let paddingY = paddingX;
let resized = true;

const view = new Actor(select("#view"));
const world = new Actor(select("#world"));
const bee = new Actor(select("#bee"), {
  bounds: world
});

const scrollBounds = new Actor(select("#scroll-bounds"), {
  resizable: true
});

const camera = new Camera(world, view, {
  scrollBounds,
  paddingX, 
  paddingY
});

bee.centerOn(view);

window.addEventListener("load", onLoad);

//
// UPDATE
// =========================================================================== 
function update(delta) {
   
  if (resized) {
    
    view.refresh();
    world.refresh();
    bee.refresh();
    camera.refresh();
    resized = false;
  }
  
  let x = 0;
  let y = 0;
  
  if (keyboard.isDown(Key.LEFT)) {
    x = -1;
  } else if (keyboard.isDown(Key.RIGHT)) {
    x = 1;
  }
  
  if (keyboard.isDown(Key.UP)) {
    y = -1;
  } else if (keyboard.isDown(Key.DOWN)) {
    y = 1;
  }
    
  bee.move(x, y, delta);
  camera.follow(bee, delta);  
  
  view.render();
  world.render();
  bee.render();
  scrollBounds.render();
}

//
// ON LOAD
// =========================================================================== 
function onLoad() {  
  
  keyboard.addKeys([Key.UP, Key.DOWN, Key.LEFT, Key.RIGHT]);  
  ticker.add(update);  
  window.addEventListener("resize", () => resized = true);
  window.focus();
}

//
// QUICK SETTINGS
// =========================================================================== 
const quickSettings = QuickSettings.create(5, 5, "Camera")
  .addHTML("Info", "Use arrow keys to move around.")
  .hideTitle("Info")
  .addRange("Padding X", 0, 0.5, paddingX, 0.01, value => {    
    paddingX = value;
    if (camera.paddingX !== paddingX) {
      camera.setPadding(paddingX, paddingY);
    }
  })
  .addRange("Padding Y", 0, 0.5, paddingY, 0.01, value => {    
    paddingY = value;
    if (camera.paddingY !== paddingY) {
      camera.setPadding(paddingX, paddingY);
    }
  })
//   .addRange("Rotation", -360, 360, rotation, 1, value => {    
//     rotation = value;  
//     TweenLite.to([world.element, scrollBounds.element], 0.2, {
//       rotation: rotation + "_short"
//     });
//   })
//   // .addRange("Scale", 0.05, 10, scale, 0.01, value => {    
//   .addRange("Scale", 1, 10, scale, 0.01, value => {    
//     scale = value;        
//     TweenLite.to([world.element, scrollBounds.element], 0.2, {
//       scale: scale
//     });    
//   })
//   .addButton("Reset", () => {
    
//     quickSettings
//       .setValue("Padding X", 0.25)
//       .setValue("Padding Y", 0.25)
//       .setValue("Scale", 1)
//       .setValue("Rotation", 0)
//   })
  
function clamp(value, min, max) {
  return value < min ? min : (value > max ? max : value);
}
              
            
!
999px

Console