Photo slices

Click on the screen to increase or decrease the number of slices. Move the cursor for some interaction. Picture from Sukanto Debnath http://www.flickr.com/photos/sukanto_debnath/3081836966/

by Javier Graciá Carpio

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

JavaScript

var sketch = function(p) {
	// Global variables
	var originalImg;
	var slices;
	var sliceSize = 8;

	// Load the image before the sketch is run
	p.preload = function() {
		originalImg = p.loadImage("http://farm3.staticflickr.com/2340/2354607553_9996a0c8fc.jpg");
	};

	// Initial setup
	p.setup = function() {
		// Create the canvas
		var canvas = p.createCanvas(1.5 * originalImg.width, originalImg.height);

		// Create new slices each time the mouse is pressed inside the canvas
		canvas.mousePressed(createNewSlices);

		// Create the slices
		slices = createSlices(originalImg);
	};

	// Execute the sketch
	p.draw = function() {
		// Clean the canvas
		p.background(0);

		// Update the slides positions and check if the mouse pushed them
		for (var i = 0; i < slices.length; i++) {
			slices[i].checkPush();
			slices[i].update();
			slices[i].paint();
		}
	};

	/*
	 * This function creates a set of slices with a given slice size
	 */
	function createSlices(img) {
		var nSlices = p.floor(img.width / sliceSize);
		var s = [];

		for (var i = 0; i < nSlices; i++) {
			s[i] = new Slice(i * sliceSize, sliceSize, img);
		}

		return s;
	}

	/*
	 * This function changes the slice size and creates a new set of slices
	 */
	function createNewSlices() {
		// Decrease the slice size by a factor of 2
		sliceSize /= 2;

		// If the size is too small, set it to a larger value
		if (sliceSize < 2) {
			sliceSize = 32;
		}

		// Create the new slices
		slices = createSlices(originalImg);
	}

	/*
	 * The Slice class
	 */
	function Slice(xImg, size, img) {
		// Create the slice image
		this.imgSlice = img.get(xImg, 0, size, img.height);

		// Calculate the slice position
		this.xWithoutNoise = (p.width - img.width) / 2 + xImg;
		this.x = this.xWithoutNoise;
		this.vel = 0;

		// Define the noise properties
		this.noiseRange = 400;
		this.noiseSeed = p.random(0, 100);
		this.noiseDelta = 0;
		this.noiseStep = 0.002;
		this.noiseSmallRange = 200;
		this.noiseSmallSeed = p.random(0,...