Экспортируйте html область как изображение с html2canvas - PullRequest
0 голосов
/ 13 апреля 2020

У меня приложение React. Мне нужно иметь возможность экспортировать компонент в виде PNG / JPG. Я пытаюсь сделать это с библиотекой html2canvas.

Я пытался использовать этот наивный подход

const printDocument = () => {
  html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {
  return (
    <div className="App">
      <div id="capture" style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={printDocument}>Print</button>
    </div>
  );
}

Но я получаю сообщение об ошибке:

TypeError
(0 , _html2canvas.html2canvas) is not a function
printDocument
/src/App.js:12:14
   9 | // };
  10 | 
  11 | const printDocument = () => {
> 12 |   html2canvas(document.querySelector("#capture")).then(canvas => {
     |              ^
  13 |     document.body.appendChild(canvas);
  14 |   });
  15 | };

Как я могу достичь этого в ReactJs?

1 Ответ

1 голос
/ 13 апреля 2020

Используйте следующую инструкцию по импорту

import html2canvas from 'html2canvas';

Вы можете использовать useRef крюк реагирования

const printDocument = (domElement) => {
  html2canvas(domElement).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {

   const canvasRef = useRef()

  return (
    <div className="App">
      <div ref={canvasRef} style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={()=>printDocument(canvasRef.current)}>Print</button>
    </div>
  );
}
...