Parcourir la source

math queue completed callback

hare8999@163.com il y a 3 ans
Parent
commit
c1e46269bc
2 fichiers modifiés avec 72 ajouts et 77 suppressions
  1. 22 28
      public/collectImg/index.html
  2. 50 49
      public/collectImg/js/globalVariable.js

+ 22 - 28
public/collectImg/index.html

@@ -126,13 +126,13 @@
         return underline
       },
       // 遍历所有子元素
-      findAllEle(promiseArr, parent) {
+      async findAllEle(canvasContainer, parent) {
         for (let i of parent.childNodes) {
           if (i.nodeName === 'U') {
             parent.insertBefore(this.getUnderline(i.innerText.length), i)
             parent.removeChild(i)
           } else if (i.nodeName === 'IMG') {
-            const promise = new Promise((resolve, reject) => {
+            return new Promise((resolve, reject) => {
               i.onload = async(e) => {
                 // 如果图片存在浮动,需要手动设置容器的高度
                 if (i.style.float) {
@@ -140,47 +140,37 @@
                   qs.style.height = Math.max(qs.getBoundingClientRect().height, i.height) + 'px'
                 }
                 const { width, height } = qs.getBoundingClientRect()
-                html2canvas(qs, {
+                const imgCanvas = await html2canvas(qs, {
                   canvas: this.getCanvasWrap(width, height),
                   useCORS: true
-                }).then((canvas) => {
-                  resolve(canvas)
                 })
+                canvasContainer.push(imgCanvas)
               }
+              i.onerror = (e) => reject(e)
             })
-            promiseArr.push(promise)
           }
           if (i.hasChildNodes()) {
-            this.findAllEle(promiseArr, i)
+            await this.findAllEle(canvasContainer, i)
           }
         }
       },
-      waitingLoaingImg(cb) {
+      async waitingLoaingImg(cb) {
         let doms
         let parent
         const qs = document.querySelector('#qs')
         // 每次重置容器高度
         qs.style.height = 'auto'
-        const promiseArr = []
-        this.findAllEle(promiseArr, qs)
-        if (promiseArr.length === 0) {
+        const canvasContainer = []
+        await this.findAllEle(canvasContainer, qs)
+        if (canvasContainer.length === 0) {
           const { width, height } = qs.getBoundingClientRect()
-          html2canvas(qs, {
+          const topCanvas = await html2canvas(qs, {
             canvas: this.getCanvasWrap(width, height),
             useCORS: true
-          }).then((canvas) => {
-            if (cb) {
-              cb(canvas)
-            }
-          })
-        } else {
-          Promise.all(promiseArr).then(res => {
-            // 虽然用了Promise.all,但实际假设只有一张图片
-            if (cb) {
-              cb(res[0])
-            }
           })
+          canvasContainer.push(topCanvas)
         }
+        return canvasContainer
       },
       search() {
         if (this.questionId) {
@@ -241,7 +231,6 @@
           formData.append('manual', true)
         }
         axios.post(this.domain + '/prod-api/front/questionCollection/uploadQuestionImage', formData).then(response => {
-          console.log(response)
           if (response.data.code == 200) {
             if (this.isAuto) {
               setTimeout(() => {
@@ -278,13 +267,18 @@
       MathQueueTitle(str) {//初始化公式
         if (MathQueue) {
           clearInterval(this.time)
-          MathQueue('title')
+          console.log('math queue begin', new Date().getTime(), this.data?.questionId)
+          MathQueue('title', async() => {
+            console.log('math queue end', new Date().getTime(), this.data?.questionId)
+            const canvasContainer = await this.waitingLoaingImg() // TODO: 有些题会终止运行在此,如:18343772 18343941
+            console.log('canvas download begin', new Date().getTime(), this.data?.questionId)
+            this.downLoad(str, canvasContainer[0]) // at least contains 1 element
+          })
           // setTimeout(() => {
           // this.$nextTick(() => {
           // this.downLoad(str)
-          this.waitingLoaingImg((canvas) => {
-            this.downLoad(str, canvas)
-          })
+          // const canvasContainer = await this.waitingLoaingImg()
+          // this.downLoad(str, canvasContainer[0]) // at least contains 1 element
           // })
           // }, 1000)
         } else {

+ 50 - 49
public/collectImg/js/globalVariable.js

@@ -1,60 +1,61 @@
-let isMathjaxConfig = false;//用于标识是否配置
+let isMathjaxConfig = false//用于标识是否配置
 const initMathjaxConfig = () => {
-    if (!window.MathJax) {
-        return;
+  if (!window.MathJax) {
+    return
+  }
+  window.MathJax.Hub.Config({
+    showProcessingMessages: false, //关闭js加载过程信息
+    messageStyle: 'none', //不显示信息
+    jax: ['input/TeX', 'output/HTML-CSS'],
+    tex2jax: {
+      inlineMath: [['$', '$'], ['\\(', '\\)']], //行内公式选择符
+      displayMath: [['$$', '$$'], ['\\[', '\\]']], //段内公式选择符
+      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code', 'a'] //避开某些标签
+    },
+    'HTML-CSS': {
+      availableFonts: ['STIX', 'TeX'], //可选字体
+      showMathMenu: false //关闭右击菜单显示
     }
-    window.MathJax.Hub.Config({
-        showProcessingMessages: false, //关闭js加载过程信息
-        messageStyle: "none", //不显示信息
-        jax: ["input/TeX", "output/HTML-CSS"],
-        tex2jax: {
-            inlineMath: [["$", "$"], ["\\(", "\\)"]], //行内公式选择符
-            displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段内公式选择符
-            skipTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"] //避开某些标签
-        },
-        "HTML-CSS": {
-            availableFonts: ["STIX", "TeX"], //可选字体
-            showMathMenu: false //关闭右击菜单显示
-        }
-    });
-    isMathjaxConfig = true; //配置完成,改为true
-};
-const _ensureMathjaxInit = function () {
-    if (!isMathjaxConfig) initMathjaxConfig()
+  })
+  isMathjaxConfig = true //配置完成,改为true
 }
-const _transferTikuQuestionImageUrls = function (docEle) {
-    const imgList = docEle.getElementsByTagName('img')
-    for (var i = 0; i < imgList.length; i++) {
-        const img = imgList[i]
-        const supportTagConfigs = [
-            { tag: 'tikuimages', prefix: 'https://file.mingxuejinbang.com/tikubao/tikuimages' },
-            { tag: 'mathJye', prefix: 'https://file.mingxuejinbang.com/tikubao/mathJye' }]
-        for (let index = 0; index < supportTagConfigs.length; index++) {
-            const config = supportTagConfigs[index];
-            if (_transferTikuQuestionImageUrlsByTag(img, config)) break;
-        }
+const _ensureMathjaxInit = function() {
+  if (!isMathjaxConfig) initMathjaxConfig()
+}
+const _transferTikuQuestionImageUrls = function(docEle) {
+  const imgList = docEle.getElementsByTagName('img')
+  for (var i = 0; i < imgList.length; i++) {
+    const img = imgList[i]
+    const supportTagConfigs = [
+      { tag: 'tikuimages', prefix: 'https://file.mingxuejinbang.com/tikubao/tikuimages' },
+      { tag: 'mathJye', prefix: 'https://file.mingxuejinbang.com/tikubao/mathJye' }]
+    for (let index = 0; index < supportTagConfigs.length; index++) {
+      const config = supportTagConfigs[index]
+      if (_transferTikuQuestionImageUrlsByTag(img, config)) break
     }
+  }
 }
 
-const _transferTikuQuestionImageUrlsByTag = function (img, config) {
-    let srcParams = img.src.split(config.tag)
-    if (srcParams.length > 1) {
-        img.src = config.prefix + srcParams[1]
-        return true
-    }
-    return false
+const _transferTikuQuestionImageUrlsByTag = function(img, config) {
+  let srcParams = img.src.split(config.tag)
+  if (srcParams.length > 1) {
+    img.src = config.prefix + srcParams[1]
+    return true
+  }
+  return false
 }
 
-const MathQueue = function (elementId) {
-    _ensureMathjaxInit();
-    const docEle = document.getElementById(elementId);
-    if (!docEle) return;
-    _transferTikuQuestionImageUrls(docEle);
+const MathQueue = function(elementId, callback) {
+  _ensureMathjaxInit()
+  const docEle = document.getElementById(elementId)
+  if (!docEle) return
+  _transferTikuQuestionImageUrls(docEle)
 
-    if (!window.MathJax) {
-        return;
-    }
-    window.MathJax.Hub.Queue(["Typeset", window.MathJax.Hub, docEle]);
-};
+  if (!window.MathJax) {
+    return
+  }
+  window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, docEle])
+  if (typeof callback === 'function') window.MathJax.Hub.Queue(callback)
+}