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属性,那点击按钮下载图片时,谷歌浏览器就会报错

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

      

  • 相关阅读:
    Kaka's Matrix Travels
    Cable TV Network
    LightOJ 1137
    SPOJ AMR11E Distinct Primes 基础数论
    HDU 5533Dancing Stars on Me 基础几何
    POJ 1014 / HDU 1059 Dividing 多重背包+二进制分解
    vijos 1180 选课 树形DP
    vijos 1313 金明的预算方案 树形DP
    LightOJ 1062
    vijos 1464 积木游戏 DP
  • 原文地址:https://www.cnblogs.com/minorf/p/13025793.html
Copyright © 2011-2022 走看看