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

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

Simplication of for loop

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