index.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <!doctype html>
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
  3. <body>
  4. <h1>Select an image:</h1>
  5. <a href="smiley.svg">smiley.svg</a>
  6. <br>
  7. <a href="../../images/logo.png">logo.png</a>
  8. </body>
  9. <script>
  10. $('a').click(function() {
  11. var href = this.href;
  12. // Convert Non-SVG images to data URL first
  13. // (this could also have been done server-side by the library)
  14. if(this.href.indexOf('.svg') === -1) {
  15. var meta_str = JSON.stringify({
  16. name: $(this).text(),
  17. id: href
  18. });
  19. window.top.postMessage(meta_str, "*");
  20. var img = new Image();
  21. img.onload = function() {
  22. var canvas = document.createElement("canvas");
  23. canvas.width = this.width;
  24. canvas.height = this.height;
  25. // load the raster image into the canvas
  26. canvas.getContext("2d").drawImage(this,0,0);
  27. // retrieve the data: URL
  28. try {
  29. var dataurl = canvas.toDataURL();
  30. } catch(err) {
  31. // This fails in Firefox with file:// URLs :(
  32. alert("Data URL conversion failed: " + err);
  33. var dataurl = "";
  34. }
  35. window.top.postMessage('|' + href + '|' + dataurl, "*");
  36. }
  37. img.src = href;
  38. } else {
  39. // Send metadata (also indicates file is about to be sent)
  40. var meta_str = JSON.stringify({
  41. name: $(this).text(),
  42. id: href
  43. });
  44. window.top.postMessage(meta_str, "*");
  45. // Do ajax request for image's href value
  46. $.get(href, function(data) {
  47. data = '|' + href + '|' + data;
  48. // This is where the magic happens!
  49. window.top.postMessage(data, "*");
  50. }, 'html'); // 'html' is necessary to keep returned data as a string
  51. }
  52. return false;
  53. });
  54. </script>