【问题标题】:react canvas reference to blob?对 blob 的画布引用做出反应?
【发布时间】:2021-02-13 07:55:17
【问题描述】:

所以我想要一个画布元素作为反应中的 blob,用本地打印机打印它。请不要介意所有的打印机逻辑。它成功地将画布打印为一个反应元素,所以我不认为它与画布本身有任何关系。

export const barcode = (props) => {

const canvasReference = useRef(null)
const [loaded, setLoaded] = useState(false)

useEffect(() => {
  //creates the canvas with content
  bwipjs.toCanvas('barcode', ...)
  setLoaded(true)
}

if(setLoaded) {
  window.Printer.init(
    (printer) => { 
      canvasReference.toBlob((blob) => { // <-- FAILS
         printer.printBlob(
           blob,  
           (msg) => {
             console.log('yay')  
           },
           (error) => {
             console.error(error)  
           }
            
         }
      }
    }, 
    (error) => { 
      console.error(error)
    }
}
return <canvas ref={canvasReference} id="barcode" />
}

TypeError: canvasReference.toBlob is not a function

如果我尝试获取canvasReference 的属性,它确认它不具有HTMLCanvasElement.toBlob() https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob 的等价物。

如何通过 react 将我的画布变成一个 blob?

【问题讨论】:

    标签: javascript reactjs canvas blob


    【解决方案1】:

    useRef 挂钩的引用存储在 current 属性中。

    canvasReference.current.toBlob()
    

    【讨论】:

    • 是的,我的错。我尝试在创建引用之前使用它。我会尽可能标记为答案:)
    【解决方案2】:

    您需要访问.current 才能访问DOM 节点。 https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2019-12-30
      • 2020-05-18
      • 2021-02-18
      • 2017-11-08
      • 2018-03-05
      • 1970-01-01
      • 2017-12-11
      • 2016-12-13
      相关资源
      最近更新 更多