reactjs 如何在Fabric js中为React应用程序打印canvas?

ogq8wdun  于 2023-06-05  发布在  React
关注(0)|答案(1)|浏览(126)

下面是我的代码,我声明了一个id为'mycanvas'的canvas,但现在我需要打印它。当我尝试打印时,它不显示画布图像。问题是,我在变量canvasEl中遗漏了一些东西。我需要帮助

const canvasEl = useRef<HTMLCanvasElement>(null);
    
    useEffect(() => {
        const options = { 
            width: canvasWidth,
            height: canvasHeight,
            backgroundColor: 'white' 
        }
        const canvas = new fabric.Canvas(canvasEl.current, options)
        const tInput = new fabric.Text('Hello', {
                left: 100,
                top: 200,
                fill: 'Black',
                fontSize: 60
            });
        canvas.add(tInput)
        printCanvas()
        

        return () => { canvas.dispose();}
    }, [props.selectedMode, props.shouldRemoveSelectedObject])
     

    const printCanvas = () => {
      const canvasElement = document.getElementById('mycanvas') as HTMLCanvasElement
      var dataUrl = canvasElement.toDataURL()
      let windowContent = '<!DOCTYPE html>'
      windowContent += '<html>'
      windowContent += '<head><title>Print canvas</title></head>'
      windowContent += '<body>'
      windowContent += '<h1>This header is visible in preview</h1>'
      windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>'
      windowContent += '</body>'
      windowContent += '</html>'
      const printWin: any = window.open('', '', 'width=1000,height=1000');
      printWin.document.open();
      printWin.document.write(windowContent);
}
return (
    <>  
        <canvas id="mycanvas" width="300" height="300" ref={canvasEl} />
    </>
)
fwzugrvs

fwzugrvs1#

我使用了HTML2Canvas和JSPDF工具。我是这样解决的。

const printCanvas = () => {
  html2canvas(document.getElementById('mycanvas')).
    then((cv) => {
      const imgData2: string = cv.toDataURL('image/png')
      const doc = new jsPDF('l', 'px', [350, 150])
      doc.addImage(imgData2, 'PNG', 0, 0, 350, 150, '', 'FAST')
      doc.save('test.pdf')
    })
  })

相关问题