index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. /*jslint browser:true */
  3. (function () {
  4. "use strict";
  5. var openSheetMusicDisplay;
  6. var sampleFolder = process.env.STATIC_FILES_SUBFOLDER ? process.env.STATIC_FILES_SUBFOLDER + "/" : "",
  7. samples = {
  8. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  9. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  10. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  11. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  12. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  13. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  14. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  15. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  16. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  17. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  18. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  19. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  20. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  21. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  22. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  23. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  24. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  25. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  26. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  27. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  28. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  29. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  30. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  31. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  32. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  33. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  34. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  35. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  36. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  37. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  38. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  39. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  40. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  41. "Anonymous - Saltarello": "Saltarello.mxl",
  42. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  43. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  44. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  45. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  46. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  47. },
  48. zoom = 1.0,
  49. // HTML Elements in the page
  50. err,
  51. error_tr,
  52. canvas,
  53. selectSample,
  54. selectBounding,
  55. skylineDebug,
  56. bottomlineDebug,
  57. zoomIn,
  58. zoomOut,
  59. zoomDiv,
  60. custom,
  61. nextCursorBtn,
  62. resetCursorBtn,
  63. showCursorBtn,
  64. hideCursorBtn,
  65. backendSelect,
  66. debugReRenderBtn,
  67. debugClearBtn;
  68. // Initialization code
  69. function init() {
  70. var name, option;
  71. err = document.getElementById("error-td");
  72. error_tr = document.getElementById("error-tr");
  73. zoomDiv = document.getElementById("zoom-str");
  74. custom = document.createElement("option");
  75. selectSample = document.getElementById("selectSample");
  76. selectBounding = document.getElementById("selectBounding");
  77. skylineDebug = document.getElementById("skylineDebug");
  78. bottomlineDebug = document.getElementById("bottomlineDebug");
  79. zoomIn = document.getElementById("zoom-in-btn");
  80. zoomOut = document.getElementById("zoom-out-btn");
  81. canvas = document.createElement("div");
  82. nextCursorBtn = document.getElementById("next-cursor-btn");
  83. resetCursorBtn = document.getElementById("reset-cursor-btn");
  84. showCursorBtn = document.getElementById("show-cursor-btn");
  85. hideCursorBtn = document.getElementById("hide-cursor-btn");
  86. backendSelect = document.getElementById("backend-select");
  87. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  88. debugClearBtn = document.getElementById("debug-clear-btn");
  89. // Hide error
  90. error();
  91. // Create select
  92. for (name in samples) {
  93. if (samples.hasOwnProperty(name)) {
  94. option = document.createElement("option");
  95. option.value = samples[name];
  96. option.textContent = name;
  97. }
  98. selectSample.appendChild(option);
  99. }
  100. selectSample.onchange = selectSampleOnChange;
  101. if (selectBounding) {
  102. selectBounding.onchange = selectBoundingOnChange;
  103. }
  104. // Pre-select default music piece
  105. custom.appendChild(document.createTextNode("Custom"));
  106. // Create zoom controls
  107. zoomIn.onclick = function () {
  108. zoom *= 1.2;
  109. scale();
  110. };
  111. zoomOut.onclick = function () {
  112. zoom /= 1.2;
  113. scale();
  114. };
  115. if (skylineDebug) {
  116. skylineDebug.onclick = function() {
  117. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  118. }
  119. }
  120. if (bottomlineDebug) {
  121. bottomlineDebug.onclick = function() {
  122. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  123. }
  124. }
  125. if (debugReRenderBtn) {
  126. debugReRenderBtn.onclick = function() {
  127. rerender();
  128. }
  129. }
  130. if (debugClearBtn) {
  131. debugClearBtn.onclick = function() {
  132. openSheetMusicDisplay.clear();
  133. }
  134. }
  135. // Create OSMD object and canvas
  136. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  137. autoResize: true,
  138. backend: backendSelect.value,
  139. disableCursor: false,
  140. drawingParameters: "default", // try compact (instead of default)
  141. drawPartNames: true, // try false
  142. // drawTitle: false,
  143. // drawSubtitle: false,
  144. //drawFromMeasureNumber: 4,
  145. //drawUpToMeasureNumber: 8,
  146. drawFingerings: true,
  147. fingeringPosition: "auto", // left is default. try right. experimental: auto, above, below.
  148. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  149. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  150. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  151. // coloring options
  152. coloringEnabled: true,
  153. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  154. // defaultColorStem: "#BB0099",
  155. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  156. autoBeamOptions: {
  157. beam_rests: false,
  158. beam_middle_rests_only: false,
  159. //groups: [[3,4], [1,1]],
  160. maintain_stem_directions: false
  161. },
  162. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  163. // tripletsBracketed: true,
  164. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  165. });
  166. openSheetMusicDisplay.setLogLevel('info');
  167. document.body.appendChild(canvas);
  168. window.addEventListener("keydown", function(e) {
  169. var event = window.event ? window.event : e;
  170. if (event.keyCode === 39) {
  171. openSheetMusicDisplay.cursor.next();
  172. }
  173. });
  174. nextCursorBtn.addEventListener("click", function() {
  175. openSheetMusicDisplay.cursor.next();
  176. });
  177. resetCursorBtn.addEventListener("click", function() {
  178. openSheetMusicDisplay.cursor.reset();
  179. });
  180. hideCursorBtn.addEventListener("click", function() {
  181. openSheetMusicDisplay.cursor.hide();
  182. });
  183. showCursorBtn.addEventListener("click", function() {
  184. if (openSheetMusicDisplay.cursor) {
  185. openSheetMusicDisplay.cursor.show();
  186. } else {
  187. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  188. }
  189. });
  190. backendSelect.addEventListener("change", function(e) {
  191. var value = e.target.value;
  192. var createNewOsmd = true;
  193. if (createNewOsmd) {
  194. // clears the canvas element
  195. canvas.innerHTML = "";
  196. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {backend: value});
  197. openSheetMusicDisplay.setLogLevel('info');
  198. } else {
  199. // alternative, doesn't work yet, see setOptions():
  200. openSheetMusicDisplay.setOptions({backend: value});
  201. }
  202. selectSampleOnChange();
  203. });
  204. }
  205. function selectBoundingOnChange(evt) {
  206. var value = evt.target.value;
  207. openSheetMusicDisplay.DrawBoundingBox = value;
  208. }
  209. function selectSampleOnChange(str) {
  210. error();
  211. disable();
  212. var isCustom = typeof str === "string";
  213. if (!isCustom) {
  214. str = sampleFolder + selectSample.value;
  215. }
  216. zoom = 1.0;
  217. if (str.includes("measuresToDraw")) {
  218. // for debugging: draw from a random range of measures
  219. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  220. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  221. if (minMeasureToDraw > maxMeasureToDraw) {
  222. minMeasureToDraw = maxMeasureToDraw;
  223. let a = minMeasureToDraw;
  224. maxMeasureToDraw = a;
  225. }
  226. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  227. //maxMeasureToDraw = 1;
  228. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  229. openSheetMusicDisplay.setOptions({
  230. drawFromMeasureNumber: minMeasureToDraw,
  231. drawUpToMeasureNumber: maxMeasureToDraw
  232. });
  233. }
  234. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  235. if (str.includes("auto-custom-coloring")) {
  236. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  237. openSheetMusicDisplay.setOptions({
  238. coloringMode: 2,
  239. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"]
  240. // last color value of coloringSetCustom is for rest notes
  241. });
  242. } else {
  243. openSheetMusicDisplay.setOptions({coloringMode: 0});
  244. }
  245. openSheetMusicDisplay.setOptions({autoBeam: str.includes("autobeam")});
  246. openSheetMusicDisplay.setOptions({drawPartAbbreviations: !str.includes("Schubert_An_die_Musik")}); // TODO weird layout bug here. but shouldn't be in score anyways
  247. openSheetMusicDisplay.load(str).then(
  248. function() {
  249. // This gives you access to the osmd object in the console. Do not use in productive code
  250. window.osmd = openSheetMusicDisplay;
  251. return openSheetMusicDisplay.render();
  252. },
  253. function(e) {
  254. errorLoadingOrRenderingSheet(e, "rendering");
  255. }
  256. ).then(
  257. function() {
  258. return onLoadingEnd(isCustom);
  259. }, function(e) {
  260. errorLoadingOrRenderingSheet(e, "loading");
  261. onLoadingEnd(isCustom);
  262. }
  263. );
  264. }
  265. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  266. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  267. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  268. // Always giving a StackTrace might give us more and better error reports.
  269. // TODO for a release, StackTrace control could be reenabled
  270. errorString += "\n" + "StackTrace: \n" + e.stack;
  271. // }
  272. console.warn(errorString);
  273. }
  274. function onLoadingEnd(isCustom) {
  275. // Remove option from select
  276. if (!isCustom && custom.parentElement === selectSample) {
  277. selectSample.removeChild(custom);
  278. }
  279. // Enable controls again
  280. enable();
  281. }
  282. function logCanvasSize() {
  283. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  284. }
  285. function scale() {
  286. disable();
  287. window.setTimeout(function(){
  288. openSheetMusicDisplay.zoom = zoom;
  289. openSheetMusicDisplay.render();
  290. enable();
  291. }, 0);
  292. }
  293. function rerender() {
  294. disable();
  295. window.setTimeout(function(){
  296. if (openSheetMusicDisplay.IsReadyToRender()) {
  297. openSheetMusicDisplay.render();
  298. } else {
  299. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  300. }
  301. enable();
  302. }, 0);
  303. }
  304. function error(errString) {
  305. if (!errString) {
  306. error_tr.style.display = "none";
  307. } else {
  308. err.textContent = errString;
  309. error_tr.style.display = "";
  310. canvas.width = canvas.height = 0;
  311. enable();
  312. }
  313. }
  314. // Enable/Disable Controls
  315. function disable() {
  316. document.body.style.opacity = 0.3;
  317. selectSample.disabled = zoomIn.disabled = zoomOut.disabled = "disabled";
  318. }
  319. function enable() {
  320. document.body.style.opacity = 1;
  321. selectSample.disabled = zoomIn.disabled = zoomOut.disabled = "";
  322. logCanvasSize();
  323. }
  324. // Register events: load, drag&drop
  325. window.addEventListener("load", function() {
  326. init();
  327. selectSampleOnChange();
  328. });
  329. window.addEventListener("dragenter", function(event) {
  330. event.preventDefault();
  331. disable();
  332. });
  333. window.addEventListener("dragover", function(event) {
  334. event.preventDefault();
  335. });
  336. window.addEventListener("dragleave", function(event) {
  337. enable();
  338. });
  339. window.addEventListener("drop", function(event) {
  340. event.preventDefault();
  341. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  342. return;
  343. }
  344. // Add "Custom..." score
  345. selectSample.appendChild(custom);
  346. custom.selected = "selected";
  347. // Read dragged file
  348. var reader = new FileReader();
  349. reader.onload = function (res) {
  350. selectSampleOnChange(res.target.result);
  351. };
  352. var filename = event.dataTransfer.files[0].name;
  353. if (filename.toLowerCase().indexOf(".xml") > 0
  354. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  355. reader.readAsText(event.dataTransfer.files[0]);
  356. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0){
  357. reader.readAsBinaryString(event.dataTransfer.files[0]);
  358. }
  359. else {
  360. alert("No vaild .xml/.mxl/.musicxml file!");
  361. }
  362. });
  363. }());