Storing html2canvas canvas object to array

时间:2019-01-18 18:23:25

标签: reactjs html2canvas

I'm fairly new to React. I am playing with React and html2Canvas. What I am trying to do is use html2canvas to capture "screenshots" of my page but I would like to do so in such a way that I am storing all of my screenshots in a canvas array so I can pass them to a component and display each canvas object in a separate component.

For now, I am outputting the canvas array that is pushing each canvas object from the then() of the html2canvas promise. Code below:

import React, { Component } from 'react';
import html2canvas from 'html2canvas';


class ScreenshotContainer extends Component {
    getScreenshotHandler = () => {
        let canvasArray = [];
        html2canvas(document.body).then(function (canvas) {
            console.log("[html2canvas then]" + canvas);
            canvasArray.push(canvas);
        })
        console.log("[Canvas Array value: ]" + canvasArray);
    }

    render() {
        return (
            <div className="ScreenshotsContainer">
                <button onClick={this.getScreenshotHandler}>Get Screenshot!</button>
            </div>
        );
    }
}
export default ScreenshotContainer;

A console.log() shows that canvasArray appears to be empty even when an HTMLCanvasElement is received in the push. What am I doing wrong?

1 个答案:

答案 0 :(得分:0)

Try something like this:

import React, { Component } from 'react';
import html2canvas from 'html2canvas';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = { canvasArray: [] };
    this.captureRef = React.createRef();
  }

  getScreenshotHandler = () => {
    html2canvas(this.captureRef.current).then(canvas =>
      this.setState({ canvasArray: canvas }),
    );
  };

  render() {
    console.log(this.state.canvasArray); // <= you'll have your canvas el there...
    return (
      <div>
        <div ref={this.captureRef} />
        <button onClick={this.getScreenshotHandler}>Get Screenshot!</button>
      </div>
    );
  }
}

export default App;