react中将html转成图片

本文介绍了如何在React应用中使用html2canvas库来实现网页内容的截图功能。通过安装html2canvas,设置DOM元素样式,计算宽高比例,然后在组件挂载后绘制到canvas上,并转换为图片数据URL。点击按钮即可触发截图操作。

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 (
            <div id='printHtml'>
               <div onClick={this.drawCanvas}>dowmloadImg</div>
            </div>
        );
    }
}

export default Sales;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值