Pages Menu
TwitterRssFacebook
Categories Menu

Posted by on 29th August, 2013

Mesmerizing dots

Mesmerizing dots

I saw on Reddit a post titled Mesmerizing and it was just a gif with some coloured dots in motion in a particular pattern.

It was quite intriguing and I found myself staring at the thing for more than I am willing to admit.

So, it was almost midnight, I am thinking, I can probably do this in a cople of hours… right? Right? Sure, it would be a fun experiment in Javascript. And there goes my sleep…

Update: note quite finished, but I think I going in the right direction. Very little code: a loop that runs 18 times, creates the dots and animation, while the index rotates the layer that the dot is animating on by 20. I need to get the timing of the individual dots right and perhaps also the changing of colors.

Notice how all the dots just move up and down a static line. 18 dots, 18 lines angled at 20 degrees from eachother. I added a toggle button so you can see how the magic suddenly disappears when you see the lines.

dots.js - (code in progress...)

var stageWidth = 480;
var stageHeight = 320;

var stage;
var mainImage = new Image();
var radian = new Kinetic.Layer();

function init() {
	stage = new Kinetic.Stage({
	    container: 'experimentcontainer',
		width: stageWidth,
		height: stageHeight
	});

	for (var i = 1; i <= 18; i++) {
	    window.animateDot(new Kinetic.Circle({
	        radius: 5,
	        fill: '#' + (Math.random() * 0xFFFFFF << 0).toString(16),
	        stroke: 'black',
	        strokeWidth: 1,
	        offset: [0, 0]
	    }), new Kinetic.Layer(), i);
    };

	mainImage.onload = function () {
	    var image = new Kinetic.Image({
	        x: 0,
	        y: 0,
	        image: mainImage,
	        width: 480,
	        height: 320
	    });

	    window.radian.add(image);
	    stage.add(window.radian);
	    window.radian.hide();
	};
    
	mainImage.src = "/private/experiments/mesmerizing/images/main_18.png";
}

function animateDot(dot, layer, index) {
    
    var amplitude = 120;
    var period = 2000;
    var centerX = stage.getWidth() / 2;
    var centerY = stage.getHeight() / 2;

    layer.move(centerX, centerY);
    layer.rotateDeg((20 * index));
    
    new Kinetic.Animation(function(frame) {
        dot.setX(
            amplitude * Math.sin(
                (frame.time + (amplitude/2 * index)) * Math.PI/period) + centerY/2
        );
    }, layer.add(dot)).start();

    stage.add(layer);
}

function toggle() {
    if (window.radian.attrs.visible) {
        window.radian.hide();
    } else {
        window.radian.show();
    }
}

jQuery(function ($) {
    init();
});
Enjoy!