aboutsummaryrefslogtreecommitdiff
path: root/site/app/clipart/svgmess.js
blob: 261a21d238bb1d30efd9a53dd082b37620006ca2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
function randInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


var SVGMess = function(target) {
	var self = this;
	var url = "https://data.1bpm.net/clipart/"
	var animateTimeout;
	var items;
	var maxPointVariation = 0;
	var maxWidth = 0;
	var maxHeight = 0;
	window.image = SVG().addTo("#" + target);

	function stdcolour(str) {
		var c = $("<canvas />");
		var ctx = c[0].getContext("2d");
		ctx.fillStyle = str;
		var fill = ctx.fillStyle;
		c.remove();
		return fill;
	}
	

	function getMaxVar(item) {
		var itemArray = item.array();
		var maxVar = 0;
		var vari;
		for (let a of itemArray) {
			vari = Math.abs(a[1] - a[0]);
			if (vari > maxVar) maxVar = vari;
		}
		return maxVar;
	}
	
	async function load() {
		var item;
		var pathPart = window.location.href.substr(window.location.href.lastIndexOf("/"));
		if (pathPart.indexOf("?") != -1) {
			item = pathPart.substr(pathPart.indexOf("?") + 1);
		} else {
			var req = await fetch(url + "collection1/list.json");
			var list = await req.json();
			item = list.files[Math.floor(Math.random() * (list.files.length - 1)) - 1];
			window.history.pushState("Image", "Image", window.location.href + "?" + item);
		}
		var data = await fetch(url + "collection1/" + item);
		var src = await data.text();
		image.svg(src);
		image.size(3000, 4000);
		items = image.find("polygon");
		
		var vari, bbox;
		for (let i of items) {
			vari = getMaxVar(i);
			bbox = i.bbox();
			if (vari > maxPointVariation) maxPointVariation = vari;
			if (bbox.w > maxWidth) maxWidth = bbox.w;
			if (bbox.h > maxHeight) maxHeight = bbox.h;
		}
		
		self.items = items;
	}

	function animate() {
		var posXmax = 300;
		var posYmax = 300;
		var item = items[Math.floor(Math.random() * (items.length - 1))];
		var variation = getMaxVar(item) / maxPointVariation;
		var fill = stdcolour(item.css().fill);
		var bbox = item.bbox();
		var colourRatio = Number("0x" + fill.substr(1)) / 16777215;
		var duration = randInt(20, 500);
		var posX = randInt(0, posXmax);
		var posY = randInt(0, posYmax);
		item.animate(duration, 0, "now")
			.move(posX, posY)
			//.rotate(randInt(1, 360)); //scale(2);
		var timeout = randInt(20, 500);
		animateTimeout = setTimeout(animate, timeout);
		var args = [
			0, duration / 1000, 
			bbox.x / posXmax, bbox.y / posYmax, 
			posX / posXmax, posY / posYmax,
			colourRatio, variation,
			bbox.w / maxWidth, bbox.h / maxHeight
		];
		app.insertScore("playback", args);
	}
	
	this.run = function() {
		animate();
	};

	load();
};