• 使用html2canvas将html通过canvas转换成图片


      html2canvas官网: http://html2canvas.hertzen.com/documentation

    一、html2canvas的兼容性

      根据官网给出的API,html2canvas的兼容性如下

      1、Firefox 3.5+

      2、Google Chrome

      3、Opera 12+

      4、IE9+

      5、Edge

      6、Safari 6+

    二、下载使用html2canvas插件  

      1、通过npm安装html2canvas

    npm install html2canvas

      2、在项目中通过import引入

    import html2canvas from 'html2canvas'

    三、html2canvas的常用的可用参数

    参数名称 类型 默认值 描述
    allowTaint boolean false 是否允许跨域图像污染画布
    backgroundColor string #fff canvas的背景颜色,如果没有设定默认透明,也可以使用rgba
    width number null canvas画布的宽度
    height number null canvas画布的高度
    proxy string null 代理地址
    useCORS boolean false 是否尝试使用CORS从服务器加载图像
    scale number 1 缩放比例,默认为1

    四、基本语法

    html2canvas(element,options).then((canvas) =>{})

      element:所需要截图的元素,doucument.getElementById获取

      options:配置的参数

      cavans:截图后返回的最后一个cavans

    五、html2canvas的使用

    import React from 'react';
    import { Button } from 'antd';
    import html2canvas from 'html2canvas'
    export default () => {
      const canvasImg = () => {
        let canvasEle: any = document.getElementById('html2canvasTest')  //获取元素
        html2canvas(canvasEle, {
           200, //设置canvas的宽度
          scale: 2,//缩放
        }).then((canvas) => {
          //处理你生成的canvas
          // document.body.appendChild(canvas);
          let a = document.createElement('a');
          a.setAttribute('href', canvas.toDataURL());  //toDataUrl:将canvas画布信息转化为base64格式图片
          a.setAttribute('download', 'downImg')  //这个是必须的,否则会报错
          a.setAttribute('target', '_self');
          a.click()
        })
      }
      return (
        <div >
          <div id="html2canvasTest">
            <p style={{ color: 'red', background: '#f5f5f5', padding: '20px', border: '1px solid red',  '200px' }}>
              html2canvas将html通过canvas转换成图片
          </p>
          </div>
          <Button onClick={canvasImg}>点击生成图片并下载</Button>
        </div>
      );
    }

      注意:如果a标签没有添加download属性,那点击按钮下载图片时,谷歌浏览器就会报错

      点击下载按钮后,下载成功:

      

  • 相关阅读:
    redis实现分布式缓存
    redis持久化
    Redis五种数据类型
    Azure Digital Twins(1)-创建实例并设置角色
    Azure Digital Twins(2)- 在本地使用ADT Explorer 管理数字孪生
    Azure Digital Twins(3)- 数字孪生体和数字孪生图
    Azure + 5G + AI + IOT可以这么玩
    使用Azure Storage API 上传 文件解决微信小程序中上传图片的问题
    Azure入门(1)- Azure核心概念
    利用 Management Group 和Policy 控制Azure 指定资源的创建
  • 原文地址:https://www.cnblogs.com/minorf/p/13025793.html
Copyright © 2020-2023  润新知