Source: sample/meteor-shower/app.js

  1. "use strict";
  2. /**
  3. * Create a meteor shower sample application.
  4. * @param {HTMLElement} container A application container.
  5. * @param {number} width The width of canvas.
  6. * @param {number} height The height of canvas.
  7. * @param {string} backcolor1 A background color for UI-thread.
  8. * @param {string} backcolor2 A background color for Worker-thread.
  9. * @returns {undefined}
  10. */
  11. function App(container, width, height, backcolor1, backcolor2) {
  12. container.insertAdjacentHTML("beforeend", `
  13. <input type="radio" id="workerUsageNoUse" name="workerUsage" value="nouse"
  14. checked="checked"/>
  15. <label for="workerUsageNoUse">Single threading (using setInterval)</label>
  16. <input type="radio" id="workerUsageUse" name="workerUsage" value="use" />
  17. <label for="workerUsageUse">Multi threading (using worker)</label>
  18. <div style="background-color: #002">
  19. <canvas style="width:${width}px;height:${height}px"></canvas>
  20. </div>`
  21. );
  22. const canvas = container.querySelector("canvas");
  23. const ctx = canvas.getContext('2d');
  24. const singleApp = new MeteorShower(ctx);
  25. singleApp.setWidth(width);
  26. singleApp.setHeight(height);
  27. singleApp.setBackcolor(backcolor1);
  28. singleApp.setCount(1000);
  29. singleApp.initialize();
  30. const multiApp = new TransWorker();
  31. multiApp.create(
  32. "meteor-shower-worker.js",
  33. MeteorShower, this, {
  34. "fillRects": fillRects => {
  35. for(const rect of fillRects) {
  36. ctx.fillStyle = rect.fillColor;
  37. ctx.fillRect(
  38. rect.x, rect.y,
  39. rect.w, rect.h);
  40. }
  41. }
  42. });
  43. multiApp.setWidth(width, null);
  44. multiApp.setHeight(height, null);
  45. multiApp.setBackcolor(backcolor2, null);
  46. multiApp.setCount(1000, null);
  47. multiApp.initialize();
  48. let usingWorker = false;
  49. const radios = container.querySelectorAll("[name='workerUsage']");
  50. for(const inp of radios) {
  51. inp.addEventListener("change", () => {
  52. if(usingWorker) {
  53. multiApp.stop(
  54. () => singleApp.start());
  55. } else {
  56. singleApp.stop();
  57. multiApp.start();
  58. }
  59. usingWorker = (inp.value === "use");
  60. });
  61. }
  62. singleApp.start();
  63. }
  64. App(document.querySelector("#app"), 640, 480, "#004", "#044");