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="img">
  <canvas> 
</div>
<form class="settings">
  <div class="setting">
    <label for="cols">Cols:</label>
    <input type="number" name="cols" value="5" min="1" max="20">
  </div> 
  <div class="setting">
    <label for="rows">Rows:</label>
    <input type="number" name="rows" value="3" min="1" max="10">
  </div> 
  <div class="setting">
    <label for="offset">Offset:</label>
    <input type="number" name="offset" value="20" min="1" max="49">
  </div> 
  <div class="setting">
    <label for="inset">Inset: <input type="checkbox" name="inset" checked></label>
  </div>
  <div class="setting">
    <label for="grid">Grid: <input type="checkbox" name="grid"></label>
  </div>
  <div class="note">
    Click image to reform/randomise
  </div>
</form>
              
            
!

CSS

              
                * {
  margin: 0;
  padding: 0;
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
  font-size: 13px;
  font-weight: 300;
}

.img {
  position: relative;
  background: #fafafa;
}

.img::before {
  content: "";
  display: block;
  padding-bottom: 56.25%;
}

.img::after{
  content: '';
  position: absolute;
  left: 50%;
  top: 50%;
  width: 32px;
  height: 32px;
  margin: -16px 0 0 -16px;
  border-radius: 50%;
  border: 3px solid transparent;
  border-top-color: #111;
  border-right-color: #111;
  border-right-width: 5px;
  border-left-width: 0;
  animation: loader 1.5s linear infinite;
}

@keyframes loader {
  100% {
    transform: rotate(360deg);
  }
}

canvas {
  position: absolute;
  z-index: 1;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

.settings {
  display: flex;
  flex-flow: row wrap;
  padding: 10px;
}

.setting {
  display: flex;
  flex-flow: row nowrap;
  flex: 0 0 auto;
  margin-right: 20px;
}

input[type=number] {
  width: 30px;
  margin-left: 5px;
  text-align: right;
}

.note {
  flex: 0 0 auto;
  margin-left: auto;
}
              
            
!

JS

              
                const settings = {
  rows: 3,
  cols: 5,
  maxOffsetPercent: 20,
  transitionDuration: 500,
  inset: true,
  drawGrid: false,
  throttleDelay: 50,
  src: '//picsum.photos/1800/1140'
};

const $canvas = document.querySelector('canvas');
const ctx = $canvas.getContext('2d');
const $form = document.querySelector('form');
const maxes = {
  rows: 10,
  cols: 20,
  maxOffsetPercent: 49,
}

let dpr;
let canvasW;
let canvasH;
let w;
let h;
let colsMax;
let rowsMax;
let transitionStartStamp;
let transitionStop = false;
let resetImage = false;
let imageLoaded = false;
let throttleStart;
let throttleTimer;
let resizedTimer;
let previousMousePos = {
  x: 0,
  y: 0
};
let cells = [];
let subdivision = {};
let maxOffset = {};

// draw over everything to start again
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, h);

// set up grid lines (if used)
ctx.lineWidth = 1;
ctx.strokeStyle = '#000';

let img = new Image();
img.onload = _imgLoaded;

function _checkMinMaxes() {
  if (settings.rows > maxes.rows) {
    settings.rows = maxes.rows;
  }
  if (settings.rows < 1) {
    settings.rows = 1;
  }

  if (settings.cols > maxes.cols) {
    settings.cols = maxes.cols;
  }
  if (settings.cols < 1) {
    settings.cols = 1;
  }

  if (settings.maxOffsetPercent > maxes.maxOffsetPercent) {
    settings.maxOffsetPercent = maxes.maxOffsetPercent;
  }
  if (settings.maxOffsetPercent < 1) {
    settings.maxOffsetPercent = 1;
  }
}

function _setup() {
  resetImage = false;
  transitionStop = true;

  _checkMinMaxes();

  $canvas.removeAttribute('width');
  $canvas.removeAttribute('height');

  dpr = window.devicePixelRatio || 1;
  canvasW = $canvas.offsetWidth;
  canvasH = $canvas.offsetHeight;
  w = canvasW * dpr;
  h = canvasH * dpr;
  colsMax = settings.inset && settings.cols > 1 ? settings.cols + 1 : settings.cols;
  rowsMax = settings.inset && settings.rows > 1 ? settings.rows + 1 : settings.rows;

  cells = [];
  for (let i = 0; i < colsMax; i++) {
    for (let j = 0; j < rowsMax; j++) {
      cells.push({});
    }
  }

  $canvas.width = canvasW * dpr;
  $canvas.height = canvasH * dpr;

  subdivision.w = Math.round(w / settings.cols);
  subdivision.h = Math.round(h / settings.rows);

  maxOffset.x = Math.round(w / 100 * settings.maxOffsetPercent);
  maxOffset.y = Math.round(h / 100 * settings.maxOffsetPercent);

  transitionStop = false;
  if (imageLoaded) {
    _imgSetup();
    _displayImage();
  }
}

function _randomOffset(direction, pos) {
  let maxO = (direction === 'x') ? maxOffset.x : maxOffset.y;
  maxO = maxO / 2;
  let rand = Math.floor(Math.random() * (maxO + 1));
  return rand * (Math.random() < 0.5 ? -1 : 1);
}

function _imgLoaded() {
  imageLoaded = true;
  _imgSetup();
  _displayImage();
}

function _imgSetup() {
  // vals to center the crop
  let offsetTop = 0;
  let offsetLeft = 0;

  // lets take a crop of the image to conform to the canvas ratio
  let imgW = img.width;
  let imgH = Math.round(h / w * img.width);

  // if the crop height is too tall, swap so the height is the dominant factor
  if (imgH > img.height) {
    imgH = img.height;
    imgW = Math.round(w / h * imgH);
    offsetTop = 0;
    offsetLeft = Math.round((img.width - imgW) / 2);
  } else {
    offsetTop = Math.round((img.height - imgH) / 2);
  }

  // now fix for allowing max offset
  offsetLeft = offsetLeft + Math.round(imgW * (settings.maxOffsetPercent / 100));
  offsetTop = offsetTop + Math.round(imgH * (settings.maxOffsetPercent / 100));

  imgW = imgW - ((imgW * (settings.maxOffsetPercent / 100)) * 2);
  imgH = imgH - ((imgH * (settings.maxOffsetPercent / 100)) * 2);

  let imgCellW = Math.round(imgW / settings.cols);
  let imgCellH = Math.round(imgH / settings.rows);

  let imgCellDims = {
    w: imgCellW,
    h: imgCellH,
    oL: offsetLeft,
    oT: offsetTop
  };

  let i = 0;
  for (let j = 0; j < colsMax; j++) {
    for (let k = 0; k < rowsMax; k++) {
      let initX = 0;
      let initY = 0;
      let randX = _randomOffset('x', j);
      let randY = _randomOffset('y', k);
      // set up for indented items
      let modifier = {
        x: 1,
        y: 1,
        subdivision: {
          w: 0,
          h: 0,
        },
        cell: {
          w: 0,
          h: 0
        }
      };
      if (settings.cols !== colsMax) {
        if (j > 0) {
          modifier.subdivision.w = subdivision.w / -2;
          modifier.cell.w = imgCellDims.w / -2;
        }
        if (j === 0 || j === settings.cols) {
          modifier.x = 0.5;
        }
      }
      if (settings.rows !== rowsMax) {
        if (k > 0) {
          modifier.subdivision.h = subdivision.h / -2;
          modifier.cell.h = imgCellDims.h / -2;
        }
        if (k === 0 || k === settings.rows) {
          modifier.y = 0.5;
        }
      }
      // set a random offset
      initX = randX;
      initY = randY;
      // set values
      cells[i] = {
        x: initX,
        y: initY,
        x1: initX,
        y1: initY,
        x2: randX,
        y2: randY,
        w: imgCellDims.w,
        h: imgCellDims.h,
        oL: imgCellDims.oL,
        oT: imgCellDims.oT,
        modifier: modifier
      };
      i++;
    }
  }
}

function _displayImage() {
  // draw a white rect background to mask
  ctx.fillRect(0, 0, w, h);
  // draw new positions
  let i = 0;
  for (let j = 0; j < colsMax; j++) {
    for (let k = 0; k < rowsMax; k++) {
      let args = [
        img,
        Math.round((cells[i].w * j) + cells[i].x + cells[i].oL + cells[i].modifier.cell.w),
        Math.round((cells[i].h * k) + cells[i].y + cells[i].oT + cells[i].modifier.cell.h),
        Math.round(cells[i].w * cells[i].modifier.x),
        Math.round(cells[i].h * cells[i].modifier.y),
        Math.round((subdivision.w * j) + cells[i].modifier.subdivision.w),
        Math.round((subdivision.h * k) + cells[i].modifier.subdivision.h),
        Math.round(subdivision.w * cells[i].modifier.x),
        Math.round(subdivision.h * cells[i].modifier.y),
      ];
      ctx.drawImage(...args);
      if (settings.drawGrid) {
        ctx.strokeRect(
          args[5],
          args[6],
          args[7],
          args[8]
        );
      }
      i++;
    }
  }
}

function _newTargets(opts) {
  transitionStop = true;

  let i = 0;
  for (let j = 0; j < colsMax; j++) {
    for (let k = 0; k < rowsMax; k++) {
      cells[i].x1 = cells[i].x;
      cells[i].y1 = cells[i].y;
      //
      if (opts.reset) {
        cells[i].x2 = 0;
        cells[i].y2 = 0;
      }
      if (opts.random) {
        cells[i].x2 = _randomOffset('x', j);
        cells[i].y2 = _randomOffset('y', k);
      }
      if (opts.dragged) {
        // work out diffs
        let deltaX = (maxOffset.x * 0.5) * opts.dragged.x;
        let deltaY = (maxOffset.y * 0.5) * opts.dragged.y;
        // store initial values
        cells[i].x3 = (cells[i].x3 === undefined) ? cells[i].x2 : cells[i].x3;
        cells[i].y3 = (cells[i].y3 === undefined) ? cells[i].y2 : cells[i].y3;
        // make new values to display
        cells[i].x2 = Math.round(cells[i].x3 - deltaX);
        cells[i].y2 = Math.round(cells[i].y3 - deltaY);
      } else {
        cells[i].x3 = undefined;
        cells[i].y3 = undefined;
      }
      if (!opts.transition) {
        cells[i].x = cells[i].x2;
        cells[i].y = cells[i].y2;
        cells[i].x1 = cells[i].x2;
        cells[i].y1 = cells[i].y2;
      }
      i++;
    }
  }
  if (opts.transition) {
    window.requestAnimationFrame(_startTransition);
  } else {
    _displayImage();
  }
}

function _easing(t) {
  // easeOutQuad
  // https://gist.github.com/gre/1650294
  return t * (2 - t);
}

function _step(timestamp) {
  if (transitionStop) {
    return;
  }
  if (timestamp - transitionStartStamp >= settings.transitionDuration) {
    transitionStop = true;
  }
 
  let pos = (timestamp - transitionStartStamp) / settings.transitionDuration;
  pos = pos > 1 ? 1 : pos;
  let easer = _easing(pos);
  let i = 0;
  for (let j = 0; j < colsMax; j++) {
    for (let k = 0; k < rowsMax; k++) {
      let deltaX = ((cells[i].x2 - cells[i].x1) * easer);
      let deltaY = ((cells[i].y2 - cells[i].y1) * easer);
      cells[i].x = cells[i].x1 + deltaX;
      cells[i].y = cells[i].y1 + deltaY;
      i++;
    }
  }

  _displayImage();
  window.requestAnimationFrame(_step);
}

function _startTransition(timestamp) {
  transitionStop = false;
  transitionStartStamp = timestamp;
  window.requestAnimationFrame(_step);
}

function _click(event) {
  if (!resetImage) {
  resetImage = true;
  _newTargets({
    reset: true,
    transition: true,
  });
  } else {
  resetImage = false;
  _newTargets({
    random: true,
    transition: true,
  });
  }
}

function _throttledMousemove(event) {
  if (!resetImage) {
    let x = (((event.pageX || event.touches[0].clientX) - $canvas.offsetLeft) / (w * 0.5)) - 1;
    let y = (((event.pageY || event.touches[0].clientY) - $canvas.offsetTop) / (h * 0.5)) - 1;
    // normalise
    x = x < -1 ? -1 : x;
    x = x > 1 ? 1 : x;
    y = y < -1 ? -1 : y;
    y = y > 1 ? 1 : y;
    // move
    _newTargets({
      dragged: {
        x: x,
        y: y
      },
      transition: true,
    });
  }
}

function _mousemove(event) {
  if (previousMousePos.x == 0 || previousMousePos.y == 0) {
    previousMousePos.x = event.pageX || event.touches[0].clientX;
    previousMousePos.y = event.pageY || event.touches[0].clientY;
    return;
  }
  // send event at the end to move to final mouse position
  clearTimeout(throttleTimer);
  throttleTimer = setTimeout(function () {
    throttleStart = new Date().getTime();
    _throttledMousemove(event);
  }, settings.throttleDelay);
  // throttle..
  // if time between throttle intervals and a mouse movement more than 20px (to stop it feeling nervous)
  let now = new Date().getTime();
  if (now > throttleStart + settings.throttleDelay && (Math.abs((event.pageX || event.touches[0].clientX) - previousMousePos.x) > 20 || Math.abs((event.pageY || event.touches[0].clientY) - previousMousePos.y) > 20)) {
    _throttledMousemove(event);
    throttleStart = now;
    previousMousePos.x = event.pageX || event.touches[0].clientX;
    previousMousePos.y = event.pageY || event.touches[0].clientY;
  }
}

function _resized() {
  _setup();
}

function _resize() {
  clearTimeout(resizedTimer);
  resizedTimer = setTimeout(_resized, 250);
}

function _change(event) {
  const formData = new FormData($form);
  settings.inset = false;
  settings.drawGrid = false;
  formData.forEach(function(value, key){
    if (key === 'rows') {
      settings.rows = parseInt(value);
    }
    if (key === 'cols') {
      settings.cols = parseInt(value);
    }
    if (key === 'offset') {
      settings.maxOffsetPercent = parseInt(value);
    }
    if (key === 'inset') {
      settings.inset = value === 'on' ? true : false;
    }
    if (key === 'grid') {
      settings.drawGrid = value === 'on' ? true : false;
    }
  });
  _setup();
}

_setup();
img.src = settings.src;
$canvas.addEventListener('mousemove', _mousemove, false);
$canvas.addEventListener('click', _click, false);
$form.addEventListener('change', _change, false);
window.addEventListener('resize', _resize);
              
            
!
999px

Console