Skip to content

Instantly share code, notes, and snippets.

@ayamflow
Last active August 29, 2015 14:17
Show Gist options
  • Save ayamflow/9a57dddeabbcf529164b to your computer and use it in GitHub Desktop.
Save ayamflow/9a57dddeabbcf529164b to your computer and use it in GitHub Desktop.
Parallax equation

Because I never remember (work with easing too)

Canvas

var y = data.y - scrollY * data.speed;

// Container height
var targetY = size.height; // window height

var containerHeight = this.items.reduce(function(smaller, item) {
    var height = ((targetY - item.baseY - item.height) / item.speed)
    if (height < smaller) return height;
    return smaller;
  }, 0);

// perfectly sized container
return size.height - containerHeight;
  

DOM

// shift: custom offset
// position: parse style left/top
// offset: getBoundingRect - margin
// speed: 1 -> 2
var y = (scrollTop + this.shift + this.viewportTop + this.position - this.offset) * -(this.speed - 1);

Easing

var y = [ formula above ];
this.y += (y - this.y) * 0.1;

"Safe" parallax (item arrives at the correct position at the correct scrollY)

// in init
function Item(x, y) {
    this.oy = y;
}

Item.prototype.update = function(scrollY, centerY) {
    // Virtual row position
    this.oy = data.y - scrollY;
  // distance between virtual row & center of screen
    var dist = (this.oy - centerY);
    if (dist < 0) dist = -dist;

  // Offset is based on dist & direction
  var offsetY = speed * dist;
  var direction = this.oy > centerY ? -1 : 1;

  // Position of item is position of row + offset
  // so the item in screen is always at it's "real" position
  // and its offset is capped to half the screen height
  this.y = this.oy + offsetY * direction;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment