Gravitational Letters

Gravitational Letters

Type to interact

       
(CSS)

* {margin: 0; padding: 0;}
canvas {display: block; background: #17293a;}
p {position: fixed; top: 26px; left: 26px; color: #fff; 
  text-transform: uppercase; 
  font-family: 'Arial', sans-serif; font-size: 18px;}


(JAVA)

/* Declare some global vars */
var canvas, ctx, width, height, letters;

/* Letter Constructor */
function Letter(char, fontSize, x, y, color) {
  var xRange, yRange;

  xRange = 4;
  yRange = 15;

  this.char = char;
  this.fontSize = fontSize;
  this.x = x;
  this.y = y;
  this.vx = -xRange / 2 + Math.random() * xRange;
  this.vy = -yRange - Math.random() * yRange;
  this.gravity = 0.4;
  this.color = color;
  this.angle = Math.random() * 360;
}

Letter.prototype = {
  constructor: Letter,
  draw: function (ctx) {
    var letter;

    letter = this.char.toUpperCase();

    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle * 180 / Math.PI);
    ctx.globalCompositeOperation = 'lighter';
    ctx.fillStyle = this.color;
    ctx.font = this.fontSize + 'em Arial';
    ctx.fillText(letter, -ctx.measureText(letter).width / 2, 20);
    ctx.restore();
  } };

/* Start the program */
init();
function init() {
  /* Assign the global vars accordingly */
  letters = [];
  canvas = document.querySelector('canvas');
  ctx = canvas.getContext('2d');
  width = canvas.width = window.innerWidth;
  height = canvas.height = window.innerHeight;

  // Populate some initial letters in order to make it look nice on codepen preview :)
  for (var i = 65; i <= 75; i++) {
    letters.push(new Letter(String.fromCharCode(i), 2 + Math.random() * 7, Math.random() * width, height + 200, '#e67e22'));
  }

  /* Start the animation */
  drawFrame();
}

function drawFrame() {
  /* Animate everything and redraw each frame */
  window.requestAnimationFrame(drawFrame, canvas);
  ctx.fillStyle = 'rgba(23, 41, 58, 0.44)';
  ctx.fillRect(0, 0, width, height);
  letters.forEach(renderLetter);
}

/* Render & update a letter */
function renderLetter(letter, index) {
  letter.x += letter.vx;
  letter.vy += letter.gravity;
  letter.y += letter.vy;
  if (height <= 600) {
    if (letter.y >= height * 5) letters.splice(letter, index);
  } else {
    if (letter.y >= height * 2.5) letters.splice(letter, index);
  }
  letter.draw(ctx);
}

/* Handle keyboard interactivity */
function keyDown(e) {
  var currentLetter, colors, colorPicker;

  colors = ['#D32F2F', '#FF4081', '#e67e22', '#f39c12',
  '#7B1FA2', '#9C27B0', '#E64A19', '#FF5722'];
  colorPicker = Math.floor(Math.random() * colors.length);

  for (var i = 48; i <= 90; i++) {
    if (e.keyCode === i) {
      currentLetter = i;
    }
  }

  letters.push(new Letter(String.fromCharCode(currentLetter), 2 + Math.random() * 7, Math.random() * width, height + 200, colors[colorPicker]));
}

/* Attach event listeners */
document.addEventListener('keydown', keyDown, false);
       

Comments