utils.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. function Utils(errorOutputId) { // eslint-disable-line no-unused-vars
  2. let self = this;
  3. this.errorOutput = document.getElementById(errorOutputId);
  4. const OPENCV_URL = 'opencv.js';
  5. this.loadOpenCv = function(onloadCallback) {
  6. let script = document.createElement('script');
  7. script.setAttribute('async', '');
  8. script.setAttribute('type', 'text/javascript');
  9. script.addEventListener('load', async () => {
  10. if (cv.getBuildInformation)
  11. {
  12. console.log(cv.getBuildInformation());
  13. onloadCallback();
  14. }
  15. else
  16. {
  17. // WASM
  18. if (cv instanceof Promise) {
  19. cv = await cv;
  20. console.log(cv.getBuildInformation());
  21. onloadCallback();
  22. } else {
  23. cv['onRuntimeInitialized']=()=>{
  24. console.log(cv.getBuildInformation());
  25. onloadCallback();
  26. }
  27. }
  28. }
  29. });
  30. script.addEventListener('error', () => {
  31. self.printError('Failed to load ' + OPENCV_URL);
  32. });
  33. script.src = OPENCV_URL;
  34. let node = document.getElementsByTagName('script')[0];
  35. node.parentNode.insertBefore(script, node);
  36. };
  37. this.createFileFromUrl = function(path, url, callback) {
  38. let request = new XMLHttpRequest();
  39. request.open('GET', url, true);
  40. request.responseType = 'arraybuffer';
  41. request.onload = function(ev) {
  42. if (request.readyState === 4) {
  43. if (request.status === 200) {
  44. let data = new Uint8Array(request.response);
  45. cv.FS_createDataFile('/', path, data, true, false, false);
  46. callback();
  47. } else {
  48. self.printError('Failed to load ' + url + ' status: ' + request.status);
  49. }
  50. }
  51. };
  52. request.send();
  53. };
  54. this.loadImageToCanvas = function(url, cavansId) {
  55. let canvas = document.getElementById(cavansId);
  56. let ctx = canvas.getContext('2d');
  57. let img = new Image();
  58. img.crossOrigin = 'anonymous';
  59. img.onload = function() {
  60. canvas.width = img.width;
  61. canvas.height = img.height;
  62. ctx.drawImage(img, 0, 0, img.width, img.height);
  63. };
  64. img.src = url;
  65. };
  66. this.executeCode = function(textAreaId) {
  67. try {
  68. this.clearError();
  69. let code = document.getElementById(textAreaId).value;
  70. eval(code);
  71. } catch (err) {
  72. this.printError(err);
  73. }
  74. };
  75. this.clearError = function() {
  76. this.errorOutput.innerHTML = '';
  77. };
  78. this.printError = function(err) {
  79. if (typeof err === 'undefined') {
  80. err = '';
  81. } else if (typeof err === 'number') {
  82. if (!isNaN(err)) {
  83. if (typeof cv !== 'undefined') {
  84. err = 'Exception: ' + cv.exceptionFromPtr(err).msg;
  85. }
  86. }
  87. } else if (typeof err === 'string') {
  88. let ptr = Number(err.split(' ')[0]);
  89. if (!isNaN(ptr)) {
  90. if (typeof cv !== 'undefined') {
  91. err = 'Exception: ' + cv.exceptionFromPtr(ptr).msg;
  92. }
  93. }
  94. } else if (err instanceof Error) {
  95. err = err.stack.replace(/\n/g, '<br>');
  96. }
  97. this.errorOutput.innerHTML = err;
  98. };
  99. this.loadCode = function(scriptId, textAreaId) {
  100. let scriptNode = document.getElementById(scriptId);
  101. let textArea = document.getElementById(textAreaId);
  102. if (scriptNode.type !== 'text/code-snippet') {
  103. throw Error('Unknown code snippet type');
  104. }
  105. textArea.value = scriptNode.text.replace(/^\n/, '');
  106. };
  107. this.addFileInputHandler = function(fileInputId, canvasId) {
  108. let inputElement = document.getElementById(fileInputId);
  109. inputElement.addEventListener('change', (e) => {
  110. let files = e.target.files;
  111. if (files.length > 0) {
  112. let imgUrl = URL.createObjectURL(files[0]);
  113. self.loadImageToCanvas(imgUrl, canvasId);
  114. }
  115. }, false);
  116. };
  117. function onVideoCanPlay() {
  118. if (self.onCameraStartedCallback) {
  119. self.onCameraStartedCallback(self.stream, self.video);
  120. }
  121. };
  122. this.startCamera = function(resolution, callback, videoId) {
  123. const constraints = {
  124. 'qvga': {width: {exact: 320}, height: {exact: 240}},
  125. 'vga': {width: {exact: 640}, height: {exact: 480}}};
  126. let video = document.getElementById(videoId);
  127. if (!video) {
  128. video = document.createElement('video');
  129. }
  130. let videoConstraint = constraints[resolution];
  131. if (!videoConstraint) {
  132. videoConstraint = true;
  133. }
  134. navigator.mediaDevices.getUserMedia({video: videoConstraint, audio: false})
  135. .then(function(stream) {
  136. video.srcObject = stream;
  137. video.play();
  138. self.video = video;
  139. self.stream = stream;
  140. self.onCameraStartedCallback = callback;
  141. video.addEventListener('canplay', onVideoCanPlay, false);
  142. })
  143. .catch(function(err) {
  144. self.printError('Camera Error: ' + err.name + ' ' + err.message);
  145. });
  146. };
  147. this.stopCamera = function() {
  148. if (this.video) {
  149. this.video.pause();
  150. this.video.srcObject = null;
  151. this.video.removeEventListener('canplay', onVideoCanPlay);
  152. }
  153. if (this.stream) {
  154. this.stream.getVideoTracks()[0].stop();
  155. }
  156. };
  157. };