utils.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { AUDIO_IMG_URL } from "./constants";
  2. /**
  3. *
  4. * @param {HTMLDivElement} editor 要操作的编辑器dom,还未想好怎么用
  5. * @param {String} tagName IMG | AUDIO
  6. * @param {String} value 相对于本地电脑资源的路径
  7. */
  8. export function insertTagToEditor(editor, tagName, value, attributes = {}) {
  9. let sel, range;
  10. if (window.getSelection) {
  11. sel = window.getSelection();
  12. if (sel.getRangeAt && sel.rangeCount) {
  13. range = sel.getRangeAt(0);
  14. range.deleteContents();
  15. // TODO:
  16. // if (tagName === "AUDIO") {
  17. // const el = document.createElement("audio");
  18. // el.src = value;
  19. // el.className = "audio";
  20. // // el.style = "height: 18px; width: 180px;";
  21. // el.controls = true;
  22. // el.controlsList = "nodownload";
  23. // // el.draggable = true;
  24. // range.insertNode(el);
  25. // }
  26. if (tagName === "IMG") {
  27. const el = document.createElement("img");
  28. // console.log(value);
  29. el.src = value;
  30. el.dataset.isImage = true;
  31. if (Object.keys(attributes).length) {
  32. Object.keys(attributes).forEach((k) => {
  33. el.setAttribute(k, attributes[k]);
  34. });
  35. }
  36. range.insertNode(el);
  37. range.collapse();
  38. }
  39. editor && editor.dispatchEvent(new Event("input"));
  40. }
  41. }
  42. }
  43. /**
  44. * 将音频路径转换为图片占位符
  45. *
  46. * @param {aduioSrc} value 相对于本地电脑资源的路径
  47. * @returns {HTMLImageElement} 图片节点
  48. */
  49. export async function audioToImageNode(audioSrc) {
  50. const duration = 1;
  51. const el = document.createElement("img");
  52. el.src = AUDIO_IMG_URL;
  53. el.dataset.isAudio = true;
  54. el.dataset.audioSrc = audioSrc;
  55. el.dataset.duration = duration;
  56. const mDuration = require("moment").unix(0);
  57. mDuration.second(duration);
  58. el.title = mDuration.format("mm:ss");
  59. el.className = "audio";
  60. return el;
  61. }
  62. /**
  63. * 获取答题点序号图片base64
  64. * @param {number} serialNo 答题点序号
  65. * @returns dataUrl
  66. */
  67. export function getAnswerPointImg(serialNo) {
  68. const canvas = document.createElement("canvas");
  69. const ctx = canvas.getContext("2d");
  70. canvas.width = 64;
  71. canvas.height = 32;
  72. ctx.font = "bolder 30px serif";
  73. ctx.textAlign = "center";
  74. ctx.textBaseline = "middle";
  75. ctx.fillText(`(${serialNo})`, 32, 16);
  76. return canvas.toDataURL();
  77. }
  78. export function base64ToBlob(base64Str) {
  79. var bytes = atob(base64Str.split(",")[1]);
  80. let arr = new Uint8Array(bytes.length);
  81. for (let i = 0; i < bytes.length; i++) {
  82. arr[i] = bytes.charCodeAt(i);
  83. }
  84. return new Blob([arr], { type: "image/png" });
  85. }