source: other-projects/nz-flag-design/trunk/main-form/kiwiana/display-svg.js@ 29964

Last change on this file since 29964 was 29964, checked in by davidb, 9 years ago

Generates dynamic list of kiwiana images to use

File size: 2.4 KB
Line 
1
2function displayFlags(img_list,$displayDiv)
3{
4 var img_list_len = img_list.length;
5
6 if (img_list_len==0) {
7 return;
8 }
9
10 img_list.sort();
11
12 var root_img_re = /^.*\/(.*?)\..*?$/;
13
14 var callback_count = 0;
15
16 var i;
17 for (i=0; i<img_list.length; i++) {
18 var img_url = img_list[i];
19 var img_matches = root_img_re.exec(img_url);
20 var title = img_matches[1];
21
22 var imageObj = new Image();
23
24 imageObj.onload = function() {
25 callback_count++;
26
27 if (callback_count == img_list_len) {
28
29 // Done => wind things up
30 doneDisplayKiwiana(img_list);
31 }
32 };
33
34
35
36 imageObj.src = img_url;
37 imageObj.height = 150;
38 imageObj.title = title.toUpperCase();
39 imageObj.country = imageObj.title;
40 imageObj.id = "flag-img-" + i;
41
42
43 var $a = $('<a></a>');
44 $a.attr("href",img_url);
45
46 $a.append(imageObj);
47
48 $displayDiv.append($a);
49 }
50}
51
52
53function doneDisplayKiwiana(img_list)
54{
55 console.log("doneDisplayKiwiana()");
56
57
58/*globals $*/
59/*jslint vars: true*/
60$('a').click(function() {'use strict';
61 var meta_str;
62 var href = this.href;
63 var target = window.parent;
64 // Convert Non-SVG images to data URL first
65 // (this could also have been done server-side by the library)
66 if (this.href.indexOf('.svg') === -1) {
67
68 meta_str = JSON.stringify({
69 name: $(this).text(),
70 id: href
71 });
72 target.postMessage(meta_str, '*');
73
74 var img = new Image();
75 img.onload = function() {
76 var canvas = document.createElement('canvas');
77 canvas.width = this.width;
78 canvas.height = this.height;
79 // load the raster image into the canvas
80 canvas.getContext('2d').drawImage(this, 0, 0);
81 // retrieve the data: URL
82 var dataurl;
83 try {
84 dataurl = canvas.toDataURL();
85 } catch(err) {
86 // This fails in Firefox with file:// URLs :(
87 alert("Data URL conversion failed: " + err);
88 dataurl = "";
89 }
90 target.postMessage('|' + href + '|' + dataurl, '*');
91 };
92 img.src = href;
93 } else {
94 // Send metadata (also indicates file is about to be sent)
95 meta_str = JSON.stringify({
96 name: $(this).text(),
97 id: href
98 });
99 target.postMessage(meta_str, '*');
100 // Do ajax request for image's href value
101 $.get(href, function(data) {
102 data = '|' + href + '|' + data;
103 // This is where the magic happens!
104 target.postMessage(data, '*');
105
106 }, 'html'); // 'html' is necessary to keep returned data as a string
107 }
108 return false;
109});
110
111}
112
Note: See TracBrowser for help on using the repository browser.