react中将html转成图片

1.安装 html2canvas

 npm install html2canvas --save

2.案例

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

class Sales extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isPrint: false,
            isInfo: false,
        };
    }

    componentDidMount () {
        const maxBoxDemo = document.getElementById('maxBox');
        const heights = document.body.clientHeight;
        maxBoxDemo.style.height = heights + 'px';
    }

    DPR = () => {
        if (window.devicePixelRatio && window.devicePixelRatio > 1) {
            return window.devicePixelRatio;
        } else {
            return 1;
        }
    }

    parseValue = (value) => {
        return parseInt(value, 10);
    }

    drawCanvas = async () => {
        // 获取想要转换的 DOM 节点
        const dom = document.getElementById('printHtml');
        // const dom = document.querySelector('printHtml');
        const box = window.getComputedStyle(dom);
        // DOM 节点计算后宽高
        const width = this.parseValue(box.width);
        const height = this.parseValue(box.height);
        // 获取像素比-防止模糊
        const scaleBy = this.DPR();
        // 创建自定义 canvas 元素
        const canvas = document.createElement('canvas');

        // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
        canvas.width = width * scaleBy;
        canvas.height = height * scaleBy;
        // 设定 canvas css宽高为 DOM 节点宽高
        canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
        // 获取画笔
        const context = canvas.getContext('2d');

        // 将所有绘制内容放大像素比倍
        context.scale(scaleBy, scaleBy);

        // 将自定义 canvas 作为配置项传入,开始绘制
        return await html2canvas(dom, { canvas }).then(canvas => {
            //document.querySelector("#canvasContainer").appendChild(canvas);
            //return canvas.toDataURL("image/png");
            return canvas.toDataURL("image/png");
        });
    };

    render () {
        return (
            
dowmloadImg
); } } export default Sales;

你可能感兴趣的:(react.js,html5,javascript)