zoukankan      html  css  js  c++  java
  • 使用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属性,那点击按钮下载图片时,谷歌浏览器就会报错

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

      

  • 相关阅读:
    DAT批处理文件语法
    TreeView控件问题汇总
    windows xp home安装iis
    【Vegas原创】网站计数器(asp)
    转载:shell python脚本互调
    转载:linux的文件属性和权限学习——分析ls命令结果
    python 正则表达式匹配中文
    Python正则表达式
    linux命令备份
    移植算法编译环境到linux【redhat9.0如何显示汉字】
  • 原文地址:https://www.cnblogs.com/minorf/p/13025793.html
Copyright © 2011-2022 走看看